A password field provides a secure way for the users to enter a password by displaying the asterisk (*) character instead of the actual characters.

However, some users may type the wrong password. To avoid such errors, you can allow the users to toggle the visibility of the password to see what they are currently typing.

To make the password visible to the user, just follow the below steps:

  1. Create an <input> field with the type of password and a <button> that will be used to toggle the visibility of the password when clicked.
  2. Add an event listener to the click event of the button.
  3. When the button is clicked, toggle the type attribute of the password field between text and password. The <input> field with type text will display the actual password.

Let us assume that you have the following two elements — a password element, and a button for toggling the visibility of the password:

<input type="password" id="password" placeholder="Enter password">
<button id="toggle">Show</button>

To toggle the visibility of the password, first select the button and password input field by using the querySelector() method:

const password = document.querySelector('#password');
const btn = document.querySelector('#toggle');

Next, attach an event listener to the click event of the button and toggle the type attribute of the password field between text and password:

btn.addEventListener('click', () => {
    const type = password.type;

    // Toggle between `text` and `password`
    if (type === 'text') {
        password.type = 'password';
    } else {
        password.type = 'text';
    }
});

That's it. You're done with toggling with visibility of the password.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: