Last active
April 30, 2019 19:13
-
-
Save Steamforge/849e47be507ca0a9080a2b473b74f57e to your computer and use it in GitHub Desktop.
A function to apply floating labels to input fields
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 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