DEV Community

Discussion on: Password show/hide button using vanilla JS

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

Even using font-awesome:

document.querySelector('input[type="password"]+i')
  .addEventListener('click', function() {
  let input = this.previousElementSibling;
  input.type = input.type == 'password' ? 'text' : 'password';
  this.className = this.className == 'fa fa-eye' ? 'fa fa-eye-slash' : 'fa fa-eye';
});
Enter fullscreen mode Exit fullscreen mode

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited

toggle() overwrites the last assigned icon!

<!DOCTYPE html>
<html lang=de>
  <meta charset=UTF-8>
  <title>Input Password</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  <style>
    label{
      position:relative;
    }
    input+i{
      user-select:none;
      cursor:pointer;
      position:absolute;
      right:3px;
      top:2px;
    }
  </style>
<label>Pass:
  <input type=password placeholder="Enter Your Password" /> 
  <i class="fa fa-eye"></i>
</label>
  <script>
    "use strict";
    document.querySelector('input[type="password"]+i')
      .addEventListener('click', function(){
      let i = this.previousElementSibling
      i.type = i.type=='password' ? 'text': 'password'
      this.classList.toggle('fa-eye-slash' )
    })
  </script>
Enter fullscreen mode Exit fullscreen mode

Collapse
 
devrohit0 profile image
Rohit Sharma

It looks more clean and now I get better understanding of it.
Thanks for it