JavaScript: Display and Conceal Password

Posted by

JAVASCRIPT SHOW HIDE PASSWORD

.password-toggle {
position: relative;
}
.password-toggle__input {
padding-right: 30px;
}
.password-toggle__btn {
position: absolute;
right: 5px;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
}

JAVASCRIPT SHOW HIDE PASSWORD

You can use JavaScript to create a show/hide functionality for passwords
on your website or web application. This can be useful for allowing users
to easily view or hide their password as they type it into a form input.

HTML Markup

Firstly, you will need to create a form input for the password and a button
for toggling the visibility of the password.

      
        <div class="password-toggle">
          <input type="password" class="password-toggle__input" id="password" />
          <button class="password-toggle__btn" id="togglePassword">Show</button>
        </div>
      
    

JavaScript Function

Next, you will need to create a JavaScript function that will toggle the
type attribute of the password input between “password” and “text” based on
the current state of the input.

      
        document.getElementById('togglePassword').addEventListener('click', function() {
          const passwordInput = document.getElementById('password');
          if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            document.getElementById('togglePassword').innerText = 'Hide';
          } else {
            passwordInput.type = 'password';
            document.getElementById('togglePassword').innerText = 'Show';
          }
        });
      
    

This JavaScript function adds an event listener to the toggle button, which
changes the type attribute of the password input between ‘password’ and ‘text’
when clicked. It also updates the text of the button to reflect the current
state of the password visibility.

Styling

Finally, you may want to style the input and button to make them visually
appealing and easy to use. Here is an example of how you might do this with
CSS:

      
        .password-toggle {
          position: relative;
        }
        .password-toggle__input {
          padding-right: 30px;
        }
        .password-toggle__btn {
          position: absolute;
          right: 5px;
          top: 50%;
          transform: translateY(-50%);
          cursor: pointer;
        }
      
    

With these steps, you can easily implement a show/hide password functionality on your website or web application using JavaScript.