How to Toggle Password Visibility in Javascript
In this tutorial, you will learn how to toggle password visibility in javascript. It is a very basic and common pattern to provide your website visitors the ability to mask and unmask a password in the login or signup form. It is only done so that a visitor can make sure that the password entered in the input field is correct.
In HTML, when you set the type of an input field as text
, it makes the text in the input field visible but if you set the type to password
, then that text will be masked with dots.
In javascript, we have access to type
property and with the help of that, we can get and set type of an input element dynamically. We are going to take advantage of it to accomplish our goal
In the following example, we have one password field and a checkbox right next to it. Depending upon the state of the checkbox, we will mask or unmask the password. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 3 elements in the HTML file (
div
,input
, andlabel
). Thediv
element is just a wrapper for the rest of the elements. - One of the
input
elements is of typecheckbox
and has text“Show”
as a label. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <div> <input type="password" placeholder="Enter Password"> <label><input type="checkbox">Show</label> </div> <script src="script.js"></script> </body> </html>
body { text-align: center; } div { display: inline-block; } input { display: inline-block; padding: 10px 20px; }
Javascript
- We have selected both the
input
elements using thedocument.querySelector()
method and stored them in theinput
andcheckbox
variables. - We have attached a
click
event listener to thecheckbox
input element. - In the event handler function, we are using the
if else
statement andchecked
property of thecheckbox
input element to verify whether the checkbox is checked or not. Thechecked
property returns a Boolean value and depending upon that, we are changing the type of theinput
usingtype
property. If checked, we will set the type totext
. Otherwise, we will set it topassword
.
let input = document.querySelector('input[type="password"]'); let checkbox = document.querySelector('input[type="checkbox"]'); checkbox.addEventListener('click', () => { if(checkbox.checked) input.type = 'text'; else input.type = 'password'; });