Skip to content

Instantly share code, notes, and snippets.

@w3collective
Created February 28, 2022 00:48
Show Gist options
  • Save w3collective/b4ce24654b1c26fe93c7e7628199f9d9 to your computer and use it in GitHub Desktop.
Save w3collective/b4ce24654b1c26fe93c7e7628199f9d9 to your computer and use it in GitHub Desktop.
Toggle password visibility using JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Add a “Show Password” checkbox to a login form with JavaScript</title>
<style>
#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");
}
#toggle-password {
display: none;
}
#toggle-password+label {
text-indent: -9999px;
display: inline-block;
width: 20px;
height: 20px;
margin-left: -32px;
cursor: pointer;
}
</style>
</head>
<body>
<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>
<script>
const password = document.getElementById("password");
const togglePassword = document.getElementById("toggle-password");
togglePassword.addEventListener("click", toggleClicked);
function toggleClicked() {
password.classList.toggle("visible");
if (this.checked) {
password.type = "text";
} else {
password.type = "password";
}
}
</script>
</body>
</html>
@w3collective
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment