Skip to content

Instantly share code, notes, and snippets.

@nchristus
Last active August 29, 2015 14:13
Show Gist options
  • Save nchristus/b944f4c53241df893b56 to your computer and use it in GitHub Desktop.
Save nchristus/b944f4c53241df893b56 to your computer and use it in GitHub Desktop.
jQuery password toggle
// ==========================================================================
// Password toggle
// ==========================================================================
// Example markup:
// <div class="pw-toggle">
// <input type="password" class="text-input" id="pw-input" data-pw="pw-password">
// </div>
(function() {
var $pwDiv = $('div.pw-toggle');
var $pwBtn = $( "<button/>", {
"class": "pw-toggle__btn",
"type": "button",
"tabindex": "-1",
text: "Show",
"data-click": "pw-btn",
"data-pw": "show"
});
try {
// Test if browser supports allowing the input type to be changed
var id = $('[data-pw="pw-password"]').attr('id');
passwordField = document.getElementById(id);
passwordField.type = 'text';
passwordField.type = 'password';
// If supported, append the toggle button and add the click function
$pwBtn.prependTo($pwDiv);
$('.pw-toggle__btn').on('click', function(){
togglePassword($(this));
});
}
catch(err) {}
})();
function togglePassword(btn) {
$parent = btn.parent();
$input = $('[data-pw="pw-password"]', $parent).clone();
state = btn.attr('data-pw');
$('[data-pw="pw-password"]', $parent).remove();
if (state == 'show') {
btn.attr('data-pw', 'hide').text('Hide');
$input.attr("type", "text").appendTo($parent);
} else if (state == 'hide') {
btn.attr('data-pw', 'show').text('Show');
$input.attr("type", "password").appendTo($parent);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment