Skip to content

Instantly share code, notes, and snippets.

@danielpowell4
Last active September 29, 2020 23:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielpowell4/82838df5ba568b99533b1bdd7124330d to your computer and use it in GitHub Desktop.
Save danielpowell4/82838df5ba568b99533b1bdd7124330d to your computer and use it in GitHub Desktop.
vanilla JS password visibility toggle
const getPasswordToggleStyle = offsetEl => {
const top = offsetEl.offsetTop + 6;
const left = offsetEl.offsetLeft + offsetEl.clientWidth - 28;
return `position: absolute; top: ${top}px; left: ${left}px; max-height: 16px; vertical-align: top; padding: 0; z-index: 7;`;
};
const addPasswordToggle = domId => {
const el = document.getElementById(domId);
if (!el) return;
// build button
const toggleBtn = document.createElement("button");
toggleBtn.classList.add("__toggle-vis");
toggleBtn.dataset.inputId = domId; // used in resize
toggleBtn.setAttribute("style", getPasswordToggleStyle(el));
// build icon
const icon = document.createElement("i");
icon.classList.add("fa", "fa-eye");
// add icon to button
toggleBtn.appendChild(icon);
// setup button onclick
toggleBtn.addEventListener("click", () => {
// - change type
if (icon.classList.contains("fa-eye")) {
el.setAttribute("type", "text");
} else if (icon.classList.contains("fa-eye-slash")) {
el.setAttribute("type", "password");
}
// - swap icon
icon.classList.toggle("fa-eye");
icon.classList.toggle("fa-eye-slash");
});
document.body.appendChild(toggleBtn);
};
const passwordInputs = document.querySelectorAll('[type="password"]');
for (let [, input] of passwordInputs.entries()) {
addPasswordToggle(input.id);
}
// reset position on resize
window.addEventListener("resize", () => {
const toggleButtons = document.querySelectorAll(".__toggle-vis");
for (let [, toggleBtn] of toggleButtons.entries()) {
let inputEl = document.getElementById(toggleBtn.dataset.inputId);
toggleBtn.setAttribute("style", getPasswordToggleStyle(inputEl));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment