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:
- Create an
<input>
field with the type ofpassword
and a<button>
that will be used to toggle the visibility of the password when clicked. - Add an event listener to the
click
event of the button. - When the button is clicked, toggle the
type
attribute of the password field betweentext
andpassword
. The<input>
field with typetext
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.