Javascript Project to Toggle Password Visibility HTML5 Field in Browser Full Project For Beginners

 

 

index.html

 

 

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>HTML DOM - Toggle password visibility</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="/css/demo.css" />
        <link rel="preconnect" href="https://fonts.gstatic.com" />
        <link
            rel="stylesheet"
            href="https://fonts.googleapis.com/css2?family=Inter&family=Source+Code+Pro&display=swap"
        />
        <style>
            .toggle {
                align-items: center;
                display: flex;
                border: 1px solid #cbd5e0;
            }
            .toggle__input {
                border: none;
                flex: 1;

                /* Misc */
                padding: 0.5rem;
            }
            .toggle__button {
                background-color: transparent;
                border: none;
                cursor: pointer;
                padding: 0.5rem;
            }
        </style>
    </head>
    <body>
        <div style="margin: 4rem auto; width: 16rem">
            <div class="toggle">
                <input type="password" class="toggle__input" autocomplete="off" id="password" />

                <button class="toggle__button" id="toggle">
                    <svg
                        viewBox="0 0 24 24"
                        style="
                            fill: none;
                            height: 24px;
                            stroke: rgba(0, 0, 0, 0.4);
                            stroke-linecap: round;
                            stroke-linejoin: round;
                            stroke-width: 1;
                            width: 24px;
                        "
                    >
                        <path
                            d="M23.5,12c0,0-5.148,6.5-11.5,6.5S0.5,12,0.5,12S5.648,5.5,12,5.5S23.5,12,23.5,12z M12,8c2.209,0,4,1.791,4,4 s-1.791,4-4,4s-4-1.791-4-4S9.791,8,12,8z M12,10c1.105,0,2,0.895,2,2s-0.895,2-2,2s-2-0.895-2-2"
                        />
                    </svg>
                </button>
            </div>
        </div>

        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const passwordEle = document.getElementById('password');
                const toggleEle = document.getElementById('toggle');

                toggleEle.addEventListener('click', function () {
                    const type = passwordEle.getAttribute('type');
                    passwordEle.setAttribute('type', type === 'password' ? 'text' : 'password');
                });
            });
        </script>
    </body>
</html>

Leave a Reply