Last active
September 29, 2020 23:35
-
-
Save danielpowell4/82838df5ba568b99533b1bdd7124330d to your computer and use it in GitHub Desktop.
vanilla JS password visibility toggle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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