Last active
August 29, 2015 14:13
-
-
Save nchristus/b944f4c53241df893b56 to your computer and use it in GitHub Desktop.
jQuery password toggle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ========================================================================== | |
// 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