Show & Hide Password Button In JavaScript

Category: Form , Javascript | September 15, 2021
Author:tahiriabdo131
Views Total:30 views
Official Page:Go to website
Last Update:September 15, 2021
License:MIT

Preview:

Show & Hide Password Button In JavaScript

Description:

A super tiny JS library that enables a button to toggle the visibility of the password string users typed.

How to use it:

1. Create a password visibility toggle button next to the password field as follows:

<!-- Password Field -->
<input type="password" id="password" placeholder="Enter Password" required>

<!-- Toggle Button -->
<button id="button" value="Show password">Show Password</button>

2. Change the ‘type’ attribute of the password field to ‘text’ so that you can retrieve the password string as plain text.

//Get the Button By Id
var button = document.getElementById("button");
//Get the Password Input By Id
var password = document.getElementById("password");
button.onclick = function() {
  //Check if the input is Empty
  if (password.value.trim().length === 0) {
      //Show alert 
      alert("The password don't must be empty")
  } else if (button.textContent == "Show password") {
      //Show Password
      password.setAttribute('type', 'text');
      //Chnage the text of the button
      button.textContent = "Hide password";
      //change the color of button to Red
      button.classList.remove('btn-primary');
      button.classList.add('btn-danger');
  } else {
      //Hide Password
      password.setAttribute('type', 'password');
      //Chnage the text of the button
      button.textContent = "Show password";
      //change the color of button to Blue
      button.classList.remove('btn-danger');
      button.classList.add('btn-primary');
  }
}

You Might Be Interested In:


Leave a Reply