DEV Community

Michael Burrows
Michael Burrows

Posted on • Edited on • Originally published at w3collective.com

Add a “Show Password” checkbox to a login form with JavaScript

[ CodePen Demo | Original Article ]

Show password functionality allows a user to check if they’re entering a password correctly.

Alt Text

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>
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

Next add an event listener that calls a toggleClicked() function when the checkbox is clicked:

togglePassword.addEventListener("click", toggleClicked);
Enter fullscreen mode Exit fullscreen mode

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";
  }
}
Enter fullscreen mode Exit fullscreen mode

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'); 
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
captaingenesisx profile image
CaptainGenesisX

Nice work, thanks for sharing. I figured out this same problem a few weeks ago. It was a fun one!