This site uses third-party cookies, learn more or accept
dark light

Password show/hide animation

Written by Max Pelic on

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 divs to show the eye icon. Here's what I ended up with:

1<div class="center">

2 <input type="password" name="password" placeholder="password">
3 <div class="eye slash" onclick="togglePW()">
4 <div></div>
5 <div></div>
6 </div>
7</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:

1function togglePW(){

2 //toggle password visibility
3
document.querySelector('.eye').classList.toggle('slash');
4 //show/hide the password
5
var password = document.querySelector('[name=password]');
6 if(password.getAttribute('type') === 'password'){
7 password.setAttribute('type', 'text');
8 } else {
9 password.setAttribute('type', 'password');
10 }
11}

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.

1.eye{

2 width:1.25em;
3 height:0.75em;
4 position:relative;
5 display:inline-block;
6 --background:#aaa;
7 --color:currentColor;
8}
9.eye div{
10 overflow:hidden;
11 height:50%;
12 position:relative;
13 margin-bottom:-1px;
14}
15.eye div:before{
16 content:'';
17 background:currentColor;
18 position:absolute;
19 left:0;
20 right:0;
21 height:300%;
22 border-radius:100%;
23}
24.eye div:last-child:before{
25 bottom:0;
26}
27.eye:before{
28 content:'';
29 position:absolute;
30 top:50%;
31 left:50%;
32 transform:translate(-50%, -50%);
33 width:0.35em;
34 height:0.35em;
35 background:var(--color);
36 border:0.1em solid var(--background);
37 border-radius:100%;
38 z-index:1;
39}
40.eye:after{
41 content:'';
42 position:absolute;
43 top:-0.15em;
44 left:calc(33.333% - 0.15em);
45 transform:rotate(45deg) scaleX(0);
46 transform-origin:left center;
47 width:90%;
48 height:0.1em;
49 background:var(--color);
50 border-top:0.1em solid var(--background);
51 z-index:2;
52 transition:transform 0.25s;
53}
54.eye.slash:after{
55 transform:rotate(45deg) scaleX(1);
56}

You can view the CodePen for this project here.

Share this article:

Previous Article: CSS units of mesaurement

Next Article: Pure CSS collapsible menu