Password show/hide animation
It’s always a good idea to add a show/hide button on any password input. For security reasons, I always like to make a password field default to hidden and give the user the option to view it.
A while back I made a password show/hide animation, and I thought I’d share it here. Here’s a link to the CodePen where you can view it in action.
Step 1 - HTML
The HTML for this project is pretty simple. I just used a div
to center the input, but you can leave that out. Other than that, there’s just an input
for the password and a few div
s to show the eye icon. Here’s what I ended up with:
<div class="center">
<input type="password" name="password" placeholder="password">
<div class="eye slash" onclick="togglePW()">
<div></div>
<div></div>
</div>
</div>
Step 2 - JavaScript
Next, I added JavaScript to toggle the slash over the eye and to show/hide the password. Here’s how I did it:
function togglePW(){
//toggle password visibility
document.querySelector('.eye').classList.toggle('slash');
//show/hide the password
var password = document.querySelector('[name=password]');
if(password.getAttribute('type') === 'password'){
password.setAttribute('type', 'text');
} else {
password.setAttribute('type', 'password');
}
}
Step 3 - CSS
Last, I added the CSS to display the eye and slash. I only included the necessary style rules here, but you can view them all on the CodePen.
The eye size is based on the font size, so it fits whatever style is applied to the document. It’s created using CSS, no SVG or image files needed.
.eye{
width:1.25em;
height:0.75em;
position:relative;
display:inline-block;
--background:#aaa;
--color:currentColor;
}
.eye div{
overflow:hidden;
height:50%;
position:relative;
margin-bottom:-1px;
}
.eye div:before{
content:'';
background:currentColor;
position:absolute;
left:0;
right:0;
height:300%;
border-radius:100%;
}
.eye div:last-child:before{
bottom:0;
}
.eye:before{
content:'';
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
width:0.35em;
height:0.35em;
background:var(--color);
border:0.1em solid var(--background);
border-radius:100%;
z-index:1;
}
.eye:after{
content:'';
position:absolute;
top:-0.15em;
left:calc(33.333% - 0.15em);
transform:rotate(45deg) scaleX(0);
transform-origin:left center;
width:90%;
height:0.1em;
background:var(--color);
border-top:0.1em solid var(--background);
z-index:2;
transition:transform 0.25s;
}
.eye.slash:after{
transform:rotate(45deg) scaleX(1);
}
You can view the CodePen for this project here.