Open In App

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 take hidden inputs. It can be shown and hidden from the user by toggling its type between text and password.

Approach

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



Example: In this example, we will see the toggling of the password visibility using HTML and JavaScript.




<!DOCTYPE html>
<html>
 
<body>
    <center>
        <h2 style="color:green">
            GeeksforGeeks
        </h2>
 
        <div>
            <form>
                Username
                <input type="text"
                       name="username"
                       autofocus=""
                       autocapitalize="none"
                       autocomplete="username"
                       required="" id="id_username">
                <br /><br />
 
                Password
                <input type="password"
                       name="password"
                       autocomplete="current-password"
                       required=""
                       id="id_password">
 
                <img src=
                     width="1%"
                     height="1%"
                     style=
                         "display: inline;
                         margin-left: -1.5%;
                         vertical-align: middle"
                     id="togglePassword">
                <br /><br />
 
                <button type="submit">
                    Login
                </button>
            </form>
        </div>
    </center>
 
    <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>
</body>
 
</html>

Output:        




Article Tags :