Hide/Show Password using Eye icon in HTML and JavaScript
In this tutorial, I will learn how to hide and show password using eye icon in HTML and JavaScript. I implemented it for one of my projects as below.
This very useful feature you should have on your login form.
There are simple two steps to follow. First, create the HTML login form. Secondly, show/hide password when the user clicks on the eye icon.
Let’s see it step-by-step. I will walk you through the complete code.
1. Create HTML Login form with Eye Icon
We are going to place the eye icon inside the password text field. We can use the eye icon from the awesome font script library.
First of all import the awesome font Stylesheet into your HTML form page.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css">
Use the tag <i>
to display the eye icon. This icon is also know as visibility eye icon.
<i class="far fa-eye" id="togglePassword"></i>
Use below CSS to put the eye icon at the end of the password text field.
margin-left: -30px; cursor: pointer;
If you are new to CSS, refer how to add CSS in HTML.
Put this tag below the passwords input field. This is how the sample form will look like with the password field.
<form method="post">
Username
<input type="text" name="username" autofocus="" autocapitalize="none" autocomplete="username" required="" id="id_username">
Password
<input type="password" name="password" autocomplete="current-password" required="" id="id_password">
<i class="far fa-eye" id="togglePassword" style="margin-left: -30px; cursor: pointer;"></i>
<button type="submit" class="btn btn-primary">Login</button>
</form>
2. Add JavaScript to Toggle Show/Hide Password
Copy and paste the below code in your JavaScript. This code is self explanatory if you are familiar with the JavaScript basics.
const togglePassword = document.querySelector('#togglePassword');
const password = document.querySelector('#id_password');
togglePassword.addEventListener('click', function (e) {
// toggle the type attribute
const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
password.setAttribute('type', type);
// toggle the eye slash icon
this.classList.toggle('fa-eye-slash');
});
You can also insert this code in your HTML page with <script>
tag.
Show/Hide Password in Django
In the sample picture shown above, I have implemented it for one of my websites developed using the Django Python framework. If you are developing it for Django, refer registration and login form in Django.
That’s all. Now you can hide and show password using eye icon in HTML with simple JavaScript and CSS code.
If you find any difficulties or need any customization, let me know in the comment section below.