Home > other >  Show/Hide icon toggle in password input field
Show/Hide icon toggle in password input field

Time:11-01

I have a simple HTML login form:

const passwordField = document.querySelector("#password");
const eyeIcon = document.querySelector("#eye");

eye.addEventListener("click", function() {
  this.classList.toggle("fa-eye-slash");
  const type = passwordField.getAttribute("type") === "password" ? "text" : "password";
  passwordField.setAttribute("type", type);
})
<script src="https://kit.fontawesome.com/6d0b0e6586.js" crossorigin="anonymous"></script>
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@200;400;500;600&display=swap" rel="stylesheet">
<div id="login-flow">
  <section>
    <h1>Welcome back.</h1>
    <form action="#" method="post">
      <label for="email">Email</label>
      <input type="email" id="email" name="email" placeholder="Email" required>
      <label for="password">Password</label>
      <div >
        <input type="password" name="password" id="password" placeholder="Password" required>
        <i  id="eye"></i>
      </div>
      <!--pass-toggle-->
      <button type="button" name="btn" id="btn-login">Login</button>
    </form>
    <div >
      <p>Don't have an account? Create one <a href="register.html">here</a>.</p>
    </div>
  </section>
</div><!--login-flow-->

Everything works great except the icon toggle. There are no warnings and the password input field changes between password and text in the console but the icon does not change. Interestingly, if I add the fa-eye-slash class to the <i> in .password-container, and this.classList.toggle to fa-eye, it works perfectly. It’s just that the icons are reversed. Why won’t it work as is?

CodePudding user response:

you attached the event listener to a non-existing variable. try this

eyeIcon.addEventListener("click", function() {
  this.classList.toggle("fa-eye-slash");
  const type = passwordField.getAttribute("type") === "password" ? "text" : "password";
  passwordField.setAttribute("type", type);
})

CodePudding user response:

here is your solution

eye.addEventListener("click", function() {

  const type = passwordField.getAttribute("type") === "password" ? "text" : "password";
  passwordField.setAttribute("type", type);

   if (passwordField.getAttribute("type") === "password") {
        eyeIcon.classList.remove("fa fa-eye");
        eyeIcon.classList.add("fa fa-eye-slash");
   } else {
        eyeIcon.classList.remove("fa fa-eye-slash");
        eyeIcon.classList.add("fa fa-eye");
   }
})
  • Related