DEV Community 👩‍💻👨‍💻

Cover image for Toggle Password Visibility
Temitope Ayodele
Temitope Ayodele

Posted on • Updated on

Toggle Password Visibility

For input types of 'password', browsers mark the user's input (typically by replacing the characters with asterisk '*'or dot '.') for security reasons. However, the user might want to confirm that his input in plain text, so there is the need for an option to toggle the password visibility.

Step 1: Create the HTML input tag [type= 'password']

  <input type='password' id='password' />
  <p>
    Show Password
    <input type='checkbox' id='checkbox' />
  </p>
Enter fullscreen mode Exit fullscreen mode

Step 2: Store selectors (Javascript)

const myInput = document.querySelector("#password");
const checkbox = document.querySelector("#checkbox");
Enter fullscreen mode Exit fullscreen mode

Step 3: Toggle visibility function

This checks toggles the input tag (myInput) type between type password and type text

const toggleVisibility = () => {
  if (myInput.type === "password") {
    myInput.type = "text";
  } else {
    myInput.type = "password";
  }
};
Enter fullscreen mode Exit fullscreen mode

Step 4: Assign this function to the checkbox onchange event

checkbox.addEventListener("change", toggleVisibility);
Enter fullscreen mode Exit fullscreen mode

Checkout this codepen for the working code.

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.