Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 29, 2022 11:28 am GMT

Password show/hide button using vanilla JS

Hello Everyone, I'm back after a long time.
In this post we are going t create a simple password show/hide button using HTML,CSS and JS.
Incase you're not able to understand what we're going to create then check out this video

HTML:

We create an input field of type="password" to Enter the password in it and for creating eye icon we use font awesome.

<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" /><input type="password" placeholder="Enter Your Password" id="pass"><button id="btn"><i id="icon"class="fa-solid fa-eye"></i></button>

CSS:

For styling, you are free to style the way you want.

JavaScript

We add an event listener to showbtn and onclick it call a function. For that we already set count= 1 and on click we increment count by 1
count += 1
Now we use if-else statement

if (count %2 == 0){     icon.classList.remove("fa-eye");    icon.classList.add("fa-eye-slash");  pass.removeAttribute("type");  }else{    icon.classList.remove("fa-eye-slash")    icon.classList.add("fa-eye");  pass.setAttribute("type","password");  }

If count is divisible by 2 then we remove fa-eye class from icon and add fa-eye-slash class to it and remove the type attribute from pass to make the password visible.

Else (count is not divisible by 2 ) then we remove fa-eye-slash class from icon and add fa-eye class to it and add attribute of type password pass to hide the password.

The complete JS code is given below

let inpPassword = document.getElementById("pass");let showbtn = document.getElementById("btn");let icon = document.getElementById("icon");let count = 1;showbtn.addEventListener("click", function() {  count += 1;  if (count %2 == 0){     icon.classList.remove("fa-eye");    icon.classList.add("fa-eye-slash");  pass.removeAttribute("type");  }else{    icon.classList.remove("fa-eye-slash")    icon.classList.add("fa-eye");  pass.setAttribute("type","password");  }});

As I'm writing this post after a long time, maybe this post is not up to that level. I'm sorry for that.

Hope you like this tutorial.


Original Link: https://dev.to/devrohit0/password-showhide-button-using-vanilla-js-27ai

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To