In today’s tutorial, we’re going to show you how to add a toggle icon next to your password to show/hide the value.
The way in which we will be adding this is using jQuery, Bootstrap 4 with Font Awesome. This can be done without Bootstrap and Font Awesome, but these days, these are often used for a lot of websites.
If you prefer, you can check this out on CodePen.
Let’s dive right into it and start with your HTML markup:
<div class="container">
<div class="row justify-content-center">
<div class="col-6">
<form>
<div class="form-group">
<label>Password</label>
<div class="input-group" id="show_hide_password">
<input class="form-control" type="password" value="mypassword">
<div class="input-group-addon">
<a href=""><i class="fa fa-eye-slash" aria-hidden="true"></i></a>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
And here’s the jQuery code to go along with it:
$(document).ready(function () {
$("#show_hide_password a").on("click", function (event) {
event.preventDefault();
$("#show_hide_password i").toggleClass('fa-eye fa-eye-slash');
if ($("#show_hide_password input").attr("type") == "text") {
$("#show_hide_password input").attr("type", "password");
} else if ($("#show_hide_password input").attr("type") == "password") {
$("#show_hide_password input").attr("type", "text");
}
});
});
And there you have it. There are other ways to do this, we can use an icon instead of integrating Font Awesome, we could even add a checkbox to reveal the password but I think it’s quite commonly used to have the eye icon with password reveals these days. Do you have another way you like to add this? Let us know in the comments below.