DEV Community

Cover image for Toggle Password Visibility
Temitope Ayodele
Temitope Ayodele

Posted on • Edited on

7 2

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay