Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

w3collective commented Feb 28, 2022

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