Skip to main content

Toggle Password Visibility

Updated 1 min readMarkdown
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>

Step 2: Store selectors (Javascript)

const myInput = document.querySelector("#password");
const checkbox = document.querySelector("#checkbox");

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";
  }
};

Step 4: Assign this function to the checkbox onchange event

checkbox.addEventListener("change", toggleVisibility);

Checkout this codepen for the working code.

About the author

  • I am a Frontend Developer (MERN stack). I am a web-accessibility and open-source advocate. I am a great team-player who has worked with awesome teams to build great products. I am self-taught with rich experience on React and Vue.

No comments yet. Be the first to comment.