#AD "Ten++ Ways to Make Money as a Developer" eBook by Florin Pop

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

Last modified October 27th 2020 | #css #js | GitHub Source Code [GitHub]

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

Show password checkbox

It helps prevent frustration when you’re sure you entered a password correctly only to find out you haven’t.

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>
Code language: HTML, XML (xml)

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");
Code language: JavaScript (javascript)

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

togglePassword.addEventListener("click", toggleClicked);
Code language: JavaScript (javascript)

toggleClicked() determines if toggle-password is “checked” and changes the field type accordingly:

function toggleClicked() { if (this.checked) { password.type = "text"; } else { password.type = "password"; } }
Code language: JavaScript (javascript)

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:

Code language: JavaScript (javascript)

Next 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"); }
Code language: CSS (css)

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; }
Code language: CSS (css)

Related Posts