About this snippet

Improve your form usability with this simple password toggle. By clicking the eye icon, users can switch the input type between text and password, which helps them avoid typos before submitting.

Size
2.3 KB
Uses
HTML, CSS, JavaScript
Loads
Nothing external
Views
499
<div class="input-group">
  <label>Password</label>
  <div class="password-field">
    <input type="password" id="passInput" placeholder="Enter your password">
    <button id="toggleBtn" type="button">
      <svg class="eye-open" viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
      <svg class="eye-close" viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:none"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line></svg>
    </button>
  </div>
</div>
.input-group {
  font-family: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  max-width: 350px;
  margin: 0 auto;
}
label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #374151;
}
.password-field {
  position: relative;
}
input {
  width: 100%;
  padding: 12px 45px 12px 15px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 1rem;
  outline: none;
  box-sizing: border-box;
  transition: border-color 0.2s;
}
input:focus {
  border-color: #3b82f6;
}
#toggleBtn {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  color: #9ca3af;
  display: flex;
  align-items: center;
}
#toggleBtn:hover {
  color: #374151;
}
const passInput = document.getElementById("passInput");
const toggleBtn = document.getElementById("toggleBtn");
const eyeOpen = document.querySelector(".eye-open");
const eyeClose = document.querySelector(".eye-close");

toggleBtn.addEventListener("click", () => {
  const type = passInput.getAttribute("type") === "password" ? "text" : "password";
  passInput.setAttribute("type", type);
  
  if (type === "text") {
    eyeOpen.style.display = "none";
    eyeClose.style.display = "block";
  } else {
    eyeOpen.style.display = "block";
    eyeClose.style.display = "none";
  }
});
Esc
↑↓ moveEnter select

Start from a template

Open an .html file, or HTML, CSS, JS, Markdown, Less or TypeScript files. You can also drop them here. Styles and scripts go into their panes.

Share

Source

Keyboard shortcuts

Save