Saturday, November 15, 2025
HomeLanguagesJavascriptHow to Toggle Password Visibility using HTML and JavaScript ?

How to Toggle Password Visibility using HTML and JavaScript ?

In this article, we will learn about how to toggle password visibility using HTML and Javascript. Passwords are those input types that appear as ******. It can be shown to the user by adding a feature of the eye icon so that the user can see the password.

Approach: The following approach will be implemented to toggle visibility of the Password:

  • We will display the use of two image icons “eye.png” and “eyeslash.png
  • Toggle these images using JavaScript.
  • We will toggle the type of input field of password ( text -> password and password -> text )

Example: In this example, we will see the toggling the Password Visibility using HTML and JavaScript.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <h2 style="color:green">
        neveropen
    </h2>
      
    <div class="col-sm-6">
        <form method="post" class="form-group ">
            Username
            <input type="text" name="username" 
                autofocus="" autocapitalize="none" 
                autocomplete="username" required=""
                id="id_username" class="form-control">
                  
            Password
            <input type="password" name="password" 
                class="form-control" 
                autocomplete="current-password" required=""
                id="id_password">
  
            <img src=
                width="1.8%" height="1%" 
                style="margin-left: -5%;display:inline;
                vertical-align: middle" 
                id="togglePassword">
  
            <button type="submit" class="btn btn-primary">
                Login
            </button>
        </form>
    </div>
</body>
  
<script>
    const togglePassword = 
        document.querySelector('#togglePassword');
          
    const password = document.querySelector('#id_password');
  
    togglePassword.addEventListener('click', function (e) {
  
        // Toggle the type attribute
        const type = password.getAttribute(
            'type') === 'password' ? 'text' : 'password';
        password.setAttribute('type', type);
  
        // Toggle the eye slash icon
        if (togglePassword.src.match(
            togglePassword.src =
        } else {
            togglePassword.src =
        }
    });
</script>
  
</html>


Output:        

toggle the Password field

RELATED ARTICLES

Most Popular

Dominic
32399 POSTS0 COMMENTS
Milvus
95 POSTS0 COMMENTS
Nango Kala
6765 POSTS0 COMMENTS
Nicole Veronica
11917 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11984 POSTS0 COMMENTS
Shaida Kate Naidoo
6889 POSTS0 COMMENTS
Ted Musemwa
7143 POSTS0 COMMENTS
Thapelo Manthata
6838 POSTS0 COMMENTS
Umr Jansen
6840 POSTS0 COMMENTS