How to toggle password visibility using JavaScript

published: 24 Mar 2022

2 min read

How to toggle password visibility using JavaScript

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.

How to toggle password visibility using JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming