In this tutorial we will see how to Show and Hide Password with Eye Icon using JavaScript. getElementById() method, .type property and .src property is used for this purpose.
Table of Contents
HTML Code
HTML code is given below, in this code we have a form tag with password type input field and img tag for the eye icon.
<form>
<div class="password">
<input type="password" placeholder="Password" id="password">
<img src="pass-hide.png" onclick="pass()" class="pass-icon" id="pass-icon">
</div>
</form>
CSS Code
CSS code is given below, in this code we have used simple CSS properties to display the eye icon along side the input type password field.
<style>
.password
{
display: inline-block;
position: relative;
border: 1px solid #000;
width:100%;
max-width:200px;
}
.password input
{
padding: 10px 5px;
outline: none;
border: 0;
width:80%;
max-width:120px;
}
.pass-icon
{
position: absolute;
top: 10px;
right: 10px;
width: 24px;
cursor: pointer;
}
</style>
JavaScript Code
JavaScript Code is given below, in this code we have used .getElementById() method to target the password type field. It's type is changed to text using HTML Dom .type property. While the img icon is changed using HTML Dom .src property.
This is done inside the main function named pass(), the function is executed on click event.
<script>
var a;
function pass()
{
if(a==1)
{
document.getElementById('password').type='password';
document.getElementById('pass-icon').src='pass-hide.png';
a=0;
}
else
{
document.getElementById('password').type='text';
document.getElementById('pass-icon').src='pass-show.png';
a=1;
}
}
</script>
Demo
Video Tutorial
Watch our video tutorial on Password Show Hide with Eye Icon using JavaScript.