Show / Hide on a password field
The login form is the most common form found on websites. Creating a login form that gives users the option to show or hide their password is therefore an element that will considerably improve your users' experience. Let's see how to do it in this article!
Want to see the code live?
Go directly to this link: demonstration
Step 1
To start, let's write our HTML code. The code is simple.
<label>
<input type="password" placeholder="Password">
<div class="password-icon">
<i data-feather="eye"></i>
<i data-feather="eye-off"></i>
</div>
</label>
<!-- ICON SCRIPT -->
<script src="https://unpkg.com/feather-icons"></script>
<script>
feather.replace();
</script>
In the previous step, we use unpkg and its collection of icons.
It's a quick solution to easily add icons: eye and eye-off which are the icons that allow us to display an eye and a slashed eye.
Step 2
Now let's style the label
and the input
.
label {
position: relative;
}
label input {
font-size: 1em;
color: #f9f9f9;
background: transparent;
padding: 1rem 1.2rem;
width: 350px;
border-radius: 5px;
border: 2px solid #7a7a7a;
transition: all 0.2s;
}
Nothing complicated here. We give a "relative" position to our label
to position our icons more easily. Then we style our password form field.
We define, for example, rounded borders with border-radius
before adding background and text colors.
Step 3
Let's now detect the click on the eye and the slashed eye.
eye.addEventListener("click", () => {
eye.style.display = "none";
eyeoff.style.display = "block";
passwordField.type = "text";
});
eyeoff.addEventListener("click", () => {
eyeoff.style.display = "none";
eye.style.display = "block";
passwordField.type = "password";
});
When the user clicks on the eye, we hide the "normal" eye icon and show the "slashed" eye icon.
Finally, we do the reverse to revert to a "hidden" input.
If you want to fully master JavaScript to do much more than just show/hide a password on a form field (input), we highly encourage you to take our complete JavaScript course immediately: learn JavaScript