How to Toggle Password Visibility Using Javascript

 

In this tutorial, you will learn how to toggle password visibility using javascript. It is very basic and common pattern to provide your website visitors the ability of masking and unmasking password in a login or sign up form. It is only done so that a visitor can make sure that the password entered by him is correct.

In HTML, when you set the input field type as text, it makes text in the input field visible but if you set the type to password, then text in the input field will be masked with dots. We have demonstrated the same in our example. Please have a look over HTML, Javascript, and CSS code given below.

 

HTML:

<!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>

 

CSS:

body {
    text-align: center;
}

div {
    display: inline-block;
}

input {
    display: inline-block;
    padding: 10px 20px;
}

 

Javascript

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';
});

 

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •