Toggle Password Visibility With Bootstrap & jQuery

Allure Web Solutions Code Snippet

In this blog post I’m discussing how to make the password field visible when tapping the little eye icon. We can do this with some custom code, but the javascript plugin I found is pretty small at only 7.89KB minified. Maybe we could write this in around 1/10th the amount of code, but it would require some annoying functionality of creating a duplicate input text field and syncing it with password field.

Also, I used bootstrap because it makes styling the little eye icon easy. I wouldn’t use bootstrap if this is the only thing you’re using it for though.

HTML

<div class="form-group has-feedback">
    <input type="password" class="form-control" id="password" placeholder="Password">
    <i class="glyphicon glyphicon-eye-open form-control-feedback"></i>
</div>

CSS

Optional to make the cursor a pointer on the eye icon (for desktops of course) instead of the pointer, since this isn’t a link. This CSS isn’t really needed for mobile apps.

#password + .glyphicon {
    cursor: pointer;
    pointer-events: all;
}

jQuery

First of all you must include jQuery and the hideShowPassword js into your project in your HTML file.

<script type=“text/javascript” src=“//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js”></script>
<script type=“text/javascript” src=“https://cdnjs.cloudflare.com/ajax/libs/hideshowpassword/2.0.8/hideShowPassword.min.js”></script>

Now the magical Javascript:

// toggle password visibility
$('#password + .glyphicon').on('click', function() {
$(this).toggleClass('glyphicon-eye-close').toggleClass('glyphicon-eye-open'); // toggle our classes for the eye icon
$('#password').togglePassword(); // activate the hideShowPassword plugin
});

CodePen Example

Mike Doubintchik

Author Mike Doubintchik

More posts by Mike Doubintchik

Leave a Reply