Skip to content

Instantly share code, notes, and snippets.

@Steamforge
Last active April 30, 2019 19:13
Show Gist options
  • Save Steamforge/849e47be507ca0a9080a2b473b74f57e to your computer and use it in GitHub Desktop.
Save Steamforge/849e47be507ca0a9080a2b473b74f57e to your computer and use it in GitHub Desktop.
A function to apply floating labels to input fields
const FloatLabel = (() => {
// add active class
const handleFocus = (e) => {
const target = e.target;
target.parentNode.classList.add('active');
target.setAttribute('placeholder', target.getAttribute('data-placeholder'));
};
// remove active class
const handleBlur = (e) => {
const target = e.target;
if(!target.value) {
target.parentNode.classList.remove('active');
}
target.removeAttribute('placeholder');
};
// register events
const bindEvents = (element) => {
const floatField = element.querySelector('input');
floatField.addEventListener('focus', handleFocus);
floatField.addEventListener('blur', handleBlur);
};
// get DOM elements
const init = () => {
const floatContainers = document.querySelectorAll('.float-container');
floatContainers.forEach((element) => {
if (element.querySelector('input').value) {
element.classList.add('active');
}
bindEvents(element);
});
};
return {
init: init
};
})();
FloatLabel.init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment