show and hide passwords in JavaScript

How to (toggle) show and hide passwords in JavaScript with an eye icon?

In this lesson, you’ll learn how to use plain JavaScript to change the visibility of a password input. It takes a few lines of code to show and hide passwords in JavaScript.
A password field allows users to enter a password safely by displaying the * character instead of the actual characters.


However, some users are likely to type the wrong password. You can add a button that allows them to toggle the password visibility to assist them in seeing the password they’re currently inputting.

We will create a sample HTML form with the input field of the password.

<div class="pass">
  <div class="overlay"></div>
    <div>
     <i class="bi bi-file-earmark-lock2-fill"></i>
      <input type="password" placeholder="Password...">
       <i class="bi bi-eye-slash-fill"></i>
    </div>
 </div>

Then the CSS code will add some styles. you can create your own styles but the javaScript part is essential.

/* */
body {
  background: #e2e2e2;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
.pass {
  background: #111625;
  border-radius: 12px;
  position: relative;
  box-shadow: 0 1rem 3rem #111625 !important;
}
.pass input {
  background: transparent;
  border: none;
  font-size: 1.2rem;
  color: #ffffff;
  padding: 15px;
}
.pass input:focus {
  outline: none;
}
.pass i {
  font-size: 1.4rem;
  padding: 1rem;
  color: #ffffff;
  transition: 0.3s;
}
.pass .bi {
  cursor: pointer;
  color: #ffffff;
  width: 1.2rem;
}
/* */

Write the JS code to make it interactive or to show and hide the password in javascript.

let input = document.querySelector(".pass input");
let eyeicon = document.querySelector(".pass .bi-eye-slash-fill");
let lockicon = document.querySelector(".pass .bi-file-earmark-lock2-fill");

eyeicon.addEventListener("click", () => {
        input.type = "text";
        eye.classList.remove("bi-eye-slash-fill");
        eye.classList.add("bi-eye-fill");
        
});

lockicon.addEventListener("click", () => {
    input.type = "password";
    eye.classList.remove("bi-eye-fill");
    eye.classList.add("bi-eye-slash-fill");
});

How to toggle the Password Visibility in JavaScript?

There is a simple way to show and hide passwords in JavaScript. you can check the input type with the conditional statements and toggle it. for example, look at the following code.

// toggle the password visibility
 eyeicon.addEventListener("click", () => {
 if(input.type == "pasword") {
   input.type = "text";
 } else {
   input.type = "password";
 }
 });