I am trying to create a password field that allows the user to click the eye icon to view or hide their password. However, on top of this, I would like to hide the password automatically when the user clicks outside the field. this requires a click and blur event. The problem is the blur event runs before the click event and runs when I click the eye icon. This causes the field to be toggled twice because it runs in the blur event block, then in the click event block.
I basically need it to allow me to toggle by clicking the eye icon and also set the field back to password type when exiting the field. I tried using onmousedown but it behaves really weird, it only works when I am stepping through on devtools.
function togglePassword(element) {
$(element).toggleClass("fa-eye fa-eye-slash");
$(element).siblings("input").each(function() {
if ($(element).hasClass('fa-eye-slash')) {
$(this).attr('type', 'text');
$(this).focus();
} else if ($(element).hasClass('fa-eye')) {
$(this).attr('type', 'password');
}
});
}
function toggleWhenExiting(element) {
console.log("focus toggle");
$(element).siblings("span").each(function() {
if ($(this).hasClass('fa-eye-slash')) {
$(element).attr('type', 'password');
$(this).toggleClass("fa-eye fa-eye-slash");
}
});
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<input type="password" id="passwordFirst" class="form-control" onblur="toggleWhenExiting(this)">
<span class="fas fa-eye" id="togglePassword" onclick="togglePassword(this)"></span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>