DEV Community

Cover image for Showing password with HTML5 and JavaScript
Walter Nascimento
Walter Nascimento

Posted on

Showing password with HTML5 and JavaScript

[Clique aqui para ler em português]

When creating a login form, it is common to require the ‘little eye’ functionality, which when clicking is displayed the password and clicking again is hidden, therefore, today we will do this functionality.

Code

First we will create the interface, we will do something simple, using only HTML.

<h1>Show Password</h1>
<form name="form_main">
  <input type="password">
  <button type="button" id="togglePass">😣</button>
</form>
Enter fullscreen mode Exit fullscreen mode

The main elements here are:

  • input = You will receive the password value, and it will be displayed in the password format (***);
  • button = Clicking will convert the password type to text type and vice versa;
"use strict";
const input = document.querySelector("input");
const button = document.querySelector("#togglePass");
button.addEventListener('click', togglePass);

function togglePass() {
  if (input.type == "password") {
    input.type = "text";
    button.textContent = "🤩";
  } else {
    input.type = "password";
    button.textContent = "😣";
  }
}
Enter fullscreen mode Exit fullscreen mode

In javascript we have, the input and the button, in the button a function called togglePass is added.

The togglePass function checks whether the input type is password, if it changes the type to text and if not, it changes to password.

ready as simple as that.

Demo

See the complete project working below.

Youtube

If you prefer to watch, I see the development on youtube (video in PT-BR).


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you! 😊😊

Top comments (0)