Forum Discussion
Converting input text to a password icon/asterisk as you type?
PhilMayor Jean-Guy-Boulay For me, neither version works as expected. Ideally, this would function perfectly if we could convert the input type to "password". When typing a password on a typical web form, pressing navigation keys like the arrow keys (left, right, up, down) doesn’t add characters to the input. They just perform their default behavior, such as moving the cursor.
The same goes for modifier keys like Shift, Ctrl, or Alt. They should not affect the input value.
To improve this, we could store a copy of the actual value typed before it’s converted to asterisks (*). This would allow us to validate what the learner really entered and potentially offer an option to reveal or retrieve the password if it's forgotten.
Here is my final script to simulate exactly that in the attached example.
const input = document.querySelector('.acc-textinput');
let rawValue = getVar("RawPassword") || "";
input.addEventListener("keydown", function(event) {
const key = event.key;
let maskedValue = getVar("MaskedPassword") || "";
const navigationKeys = ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Tab", "Enter", "Home", "End"];
if (navigationKeys.includes(key)) {
return;
}
event.preventDefault();
if (key === "Backspace" || key === "Delete") {
rawValue = rawValue.slice(0, -1);
} else if (key.length === 1) {
rawValue += key;
}
maskedValue = "*".repeat(rawValue.length);
input.value = maskedValue;
setVar("MaskedPassword", maskedValue);
setVar("RawPassword", rawValue);
});
Related Content
- 10 months ago