How To Make Show Password Button Using Javascript

You might have seen the show password button in many login forms on different websites. … Read more How To Make Show Password Button Using Javascript

You might have seen the show password button in many login forms on different websites. In this article, we will see the code to make such a show password button using javascript. 

The logic behind this show password button is straightforward. What we do is just change the “type” attribute’s value of the input to “text” from “password” when we want to make the password visible and reset it to “password” when we want to hide.

Following is the code to do so. The code is simple and self-explanatory. We have used visibility icons from google icons. You can use whatever you like to use.

If you want to see the video:

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://fonts.googleapis.com/icon?
family=Material+Icons+Outlined" rel="stylesheet">
</head>
<body>

<div class="wrapper">
        <input type="password" id="pass" name="pass">
        <span id="visiblity-toggle" 
class="material-icons-outlined">
visibility</span>
        </div>
   </body>

</html>

CSS:

   .wrapper{
            display: flex;
            align-items: center;
            border: 1px black solid;
            width: 250px;
            border-radius: 5px;
            padding: 2px;
        }
        #pass:focus{
            outline: none;
        }
        #pass{
            width: 88%;
            border: none;
            border-right: 0.25px rgb(88, 81, 81) solid;
        }
        #visiblity-toggle{
            color: grey;
            cursor: pointer;
            margin: 0 2px;
        }

Javascript:

 const pass = document.querySelector('#pass')
        const btn = document.querySelector('#visiblity-toggle')

        btn.addEventListener('click', () => {
            if (pass.type === "text") {
                pass.type = "password";
                btn.innerHTML = "visibility";
            } else {
                pass.type = "text";
                btn.innerHTML = "visibility_off";

            }
        })

If you want to download different website components and web pages you can visit here. All of them are free to use and modify.

Source: DEV Community


Categories: NewsTags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *