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.

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

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.