[ CodePen Demo | Original Article ]
Show password functionality allows a user to check if they’re entering a password correctly.
They helps prevent frustration for users who aren't sure why the password isn't working because of a miss spelling.
This tutorial will show you how this functionality can be implemented with some simple JavaScript.
First thing we need to do is setup a HTML form with a password input field field and checkbox:
<form id="login">
<div>
<input type="password" id="password" name="password" />
<input type="checkbox" id="toggle-password" />
<label for="toggle-password">Show Password</label>
</div>
</form>
Now for the JavaScript.
First let’s define a couple of variables for the password field and checkbox:
const password = document.getElementById("password");
const togglePassword = document.getElementById("toggle-password");
Next add an event listener that calls a toggleClicked()
function when the checkbox is clicked:
togglePassword.addEventListener("click", toggleClicked);
toggleClicked()
determines if toggle-password
is “checked” and changes the password field type accordingly:
function toggleClicked() {
if (this.checked) {
password.type = "text";
} else {
password.type = "password";
}
}
This works as plain text input fields don’t obscure the characters making them visible to the user.
We can take this a step further by adding an “eye” icon to indicate the toggle state of the password.
Add the following to the toggleClicked()
function to toggle a “visible” CSS class on the password field:
password.classList.toggle('visible');
Next we’ll add a “visible” icon to the password field and an “invisible” icon when the .visible
class is activated:
#password {
background-image: url("https://img.icons8.com/material-sharp/20/000000/visible.png");
background-position: 97% center;
background-repeat: no-repeat;
}
#password.visible {
background-image: url("https://img.icons8.com/material-outlined/20/000000/invisible.png");
}
Finally hide the checkbox and position the label over the icon so when clicked the visibility is toggled:
#toggle-password {
display: none;
}
#toggle-password + label {
text-indent: -9999px;
display: inline-block;
width: 20px;
height: 20px;
margin-left: -32px;
cursor: pointer;
}
Top comments (1)
Nice work, thanks for sharing. I figured out this same problem a few weeks ago. It was a fun one!