Password Show Hide with Eye Icon using JavaScript

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.

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.

Change font-size using JavaScript Get Font Size of any Tag using JavaScript Change Position of HTML Element using JavaScript How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using JavaScript How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript