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.

Get Heading Text using JavaScript Current Date in mm/dd/yyyy Format JavaScript Current Date in dd/mm/yyyy Format in JavaScript JavaScript Current Date in yyyy-mm-dd Format JavaScript Get Date Difference in Hours JavaScript Get Date Difference in Minutes JavaScript Get Date Difference in Seconds Get Last Character of String with JavaScript Trigger Button Click On Page Load JavaScript Get id Of Child Element JavaScript Get Id Of Parent Element in JavaScript Get Table Row Index onclick in JavaScript Remove specific option from Select Tag with JavaScript Change Selected Option of Select Tag with JavaScript Get Length of Text In Textarea with JavaScript Change Text Color of Select Tag Option using JavaScript Change Heading Text in JavaScript Get Input Value Length in JavaScript Toggle Button Text with JavaScript Change Background Color of Dropdown with Dropdown using JavaScript Emoji Mood Slider with HTML CSS and JavaScript Hide and Show Div with Radio Button using JavaScript Count Options In Select Tag with JavaScript Get Select Tag Text OnChange with JavaScript Change Background Color OnClick using Input Field