When I click on the icon to switch between an eye and an eye with a slash it doesn't respond immediately instead after two clicks and then after another click, the icon disappears. I don't understand why it is doing this so any help is welcome.
const pass = document.getElementById("pass");
const togglePassword = document.getElementById("togglePass");
togglePassword.addEventListener("click", function Toggle() {
if (pass.type === "password") {
pass.type = "text";
togglePassword.classList.toggle("fa-eye");
} else {
pass.type = "password";
togglePassword.classList.toggle("fa-eye-slash");
}
});
.form-control i {
position: absolute;
top: 40px;
right: 10px;
visibility: hidden;
}
.form-control i#togglePass {
margin-left: -30px;
cursor: pointer;
visibility: visible;
}
<html lang="en">
<head>
<link rel="stylesheet" href="css/styles.css">
<script src="https://kit.fontawesome.com/c90e5c3147.js" crossorigin="anonymous"></script>-
<title>Create an Account</title>
</head>
<body>
<div >
<div >
<h2>Create Account</h2>
</div>
<form action="register.php" method="POST" id="form" name="form">
<div >
<label>Password</label>
<input type="password" placeholder="Please enter a password" id="pass" name="pass">
<i id="togglePass"></i>
<small>Message</small>
</div>
</form>
</div>
<script src="js/script.js"></script>
</body>
</html>
CodePudding user response:
The problem is that you're toggling two different CSS-icon-classes conditionally. I suggest you start from one icon, to understand what is going on...
Yet, here is your temp solution:
if (pass.type === "password") {
pass.type = "text";
togglePassword.classList.remove("fa-eye-slash");
togglePassword.classList.add("fa-eye");
} else {
pass.type = "password";
togglePassword.classList.remove("fa-eye");
togglePassword.classList.add("fa-eye-slash");
}
(Instead of toggling on class, first remove unwanted, then add the other one)