# How to toggle password visibility using JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Oct 4, 2020, updated Sep 23, 2021. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-dom-toggle-password-visibility

> Learn how to toggle the visibility of a password input field by using vanilla 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](https://attacomsian.com/blog/javascript-dom-add-an-event-handler) 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 &mdash; a password element, and a button for toggling the visibility of the password:

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

To toggle the visibility of the password, first [select](https://attacomsian.com/blog/getting-dom-elements-javascript#query-selector) the button and password input field by using the `querySelector()` method:

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

Next, [attach an event listener](https://attacomsian.com/blog/javascript-dom-add-an-event-handler) to the `click` event of the button and toggle the `type` attribute of the password field between `text` and `password`:

```javascript
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.
