Menu Close

How to add Toggle for password visibility using jquery

jquery-toggle

In This 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.

Let’s start with HTML Markup:

<div class="container">
  <div class="row justify-content-center">
    <div class="col-6">
      
        <div class="form-group">
          <label>Password</label>
          <div class="input-group" id="show_hide_password">
            
            <div class="input-group-addon">
              <a href=""><i class="fa fa-eye-slash" aria-hidden="true"></i></a>
            </div>
          </div>
        </div>
      
    </div>
  </div>
</div> 

Then add the following CSS:

body {
  padding: 100px 0;
  background-color: #efefef;
}
a,
a:hover {
  color: #333;
} 

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");
    }
  });
});
	return false;
});	 

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.

Posted in CSS, HTML, jQuery, Web Technologies

You can also read...