An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
Add a Show Password checkbox to a login form with JavaScript
[ CodePen Demo | Original Article ]
Show password functionality allows a user to check if theyre entering a password correctly.
They helps prevent frustration for users who aren't sure why the password isn't working because of a miss spelling.
This tutorial will show you how this functionality can be implemented with some simple JavaScript.
First thing we need to do is setup a HTML form with a password input field field and checkbox:
<form id="login"> <div> <input type="password" id="password" name="password" /> <input type="checkbox" id="toggle-password" /> <label for="toggle-password">Show Password</label> </div></form>
Now for the JavaScript.
First lets define a couple of variables for the password field and checkbox:
const password = document.getElementById("password");const togglePassword = document.getElementById("toggle-password");
Next add an event listener that calls a toggleClicked()
function when the checkbox is clicked:
togglePassword.addEventListener("click", toggleClicked);
toggleClicked()
determines if toggle-password
is checked and changes the password field type accordingly:
function toggleClicked() { if (this.checked) { password.type = "text"; } else { password.type = "password"; }}
This works as plain text input fields dont obscure the characters making them visible to the user.
We can take this a step further by adding an eye icon to indicate the toggle state of the password.
Add the following to the toggleClicked()
function to toggle a visible CSS class on the password field:
password.classList.toggle('visible');
Next well add a visible icon to the password field and an invisible icon when the .visible
class is activated:
#password { background-image: url("https://img.icons8.com/material-sharp/20/000000/visible.png"); background-position: 97% center; background-repeat: no-repeat;}#password.visible { background-image: url("https://img.icons8.com/material-outlined/20/000000/invisible.png");}
Finally hide the checkbox and position the label over the icon so when clicked the visibility is toggled:
#toggle-password { display: none;}#toggle-password + label { text-indent: -9999px; display: inline-block; width: 20px; height: 20px; margin-left: -32px; cursor: pointer;}
Original Link: https://dev.to/michaelburrows/add-a-show-password-checkbox-to-a-login-form-with-javascript-4kbl
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To