Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Toggle password visibility using JavaScript
<!DOCTYPE html>
<html lang="en">
<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>
#password {
background-image: url("");
background-position: 97% center;
background-repeat: no-repeat;
#password.visible {
background-image: url("");
#toggle-password {
display: none;
#toggle-password+label {
text-indent: -9999px;
display: inline-block;
width: 20px;
height: 20px;
margin-left: -32px;
cursor: pointer;
<form id="login">
<input type="password" id="password" name="password" />
<input type="checkbox" id="toggle-password" />
<label for="toggle-password">Show Password</label>
const password = document.getElementById("password");
const togglePassword = document.getElementById("toggle-password");
togglePassword.addEventListener("click", toggleClicked);
function toggleClicked() {
if (this.checked) {
password.type = "text";
} else {
password.type = "password";
Copy link

w3collective commented Feb 28, 2022

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