DEV Community

Cover image for Display a user's password on input
Khwilo Kabaka
Khwilo Kabaka

Posted on • Updated on

Display a user's password on input

When designing forms, it's important to let a user correct his/her password entry on input. There are various ways to achieve this. One solution is to provide a duplicate password input field for the user to confirm the password he/she had entered in the previous input. This may prove cumbersome for the user when asked to type the same password twice and it may also degrade the user experience. To improve the user experience, we may like to provide a choice for one to reveal his/her password.

The design of the form input field has to have a button to toggle between the states: show and hide password. In order to achieve this, append a button with a text or an icon to display the two states in your HTML form:

<div class="form__group">
  <label for="password">Password</label>
  <section class="section__input">
    <input
      type="password"
      name="password"
      id="password"
      class="form__control"
    >
    <button class="toggle-displayBtn">show<button>
  </section>
</div>

Style the forms so that they appear adjacent to each other:

.section__input {
  display: flex;
}

.form__control {
  flex: 1;
}

Adding a flex of 1 ensures the input element takes as much space as possible, the toggle button takes the remaining space.

To perform the toggling between the two states, add the following code to your JavaScript file:

const passwordInput = document.getElementById('password');
const togglePasswordDisplayBtn = document.querySelector('.toggle-displayBtn');
let revealPassword = false;

togglePasswordDisplayBtn.addEventListener('click', (event) => {
  revealPassword = !revealPassword;

  if (revealPassword) {
    togglePasswordDisplayBtn.textContent = 'hide';
    passwordInput.type = 'text';
  } else {
    togglePasswordDisplayBtn.textContent = 'show';
    passwordInput.type = 'password';
  }
});

The above code gets the references to the password input field and the button to toggle between the show and hide states and declares a variable to contain the status of the toggle button. Then we listen to the click event on the toggle button. The value of revealPassword is changed between true or false when the click event on the button is triggered. If revealPassword is true, change the toggle button text content to 'hide' and change the password input type to be text. When revealPassword is false, change the toggle button text content to 'show' and change the password input type to be password.

The demo:

Alt Text

The code for this demo can be found by visiting this URL: https://github.com/khwilo/password-reveal

Latest comments (0)