Created
February 18, 2019 13:29
-
-
Save flexchar/76acae6788faeed9d42f85bb7408a894 to your computer and use it in GitHub Desktop.
TypeScript (typed JavaScript) class implementation for toggling floating label classes for form input fields (note that CSS styling is still required)
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
interface FloatingLabelConstructor { | |
fieldContainerClass: string; | |
activeFieldClass: string; | |
} | |
class FloatingLabel { | |
private fields: NodeListOf<HTMLDivElement>; | |
private className: string; | |
constructor({ fieldContainerClass, activeFieldClass } = {} as FloatingLabelConstructor) { | |
this.className = activeFieldClass; | |
this.fields = document.querySelectorAll('.' + fieldContainerClass); | |
this.init(); | |
} | |
private bindEvents(element: HTMLDivElement): void { | |
const floatField = element.querySelector('input') || element.querySelector('select'); | |
if (floatField) { | |
floatField.addEventListener('focus', this.handleFocus); | |
floatField.addEventListener('blur', this.handleBlur); | |
} | |
} | |
private handleFocus = (element: Event): void => { | |
const target = element.target as HTMLInputElement | HTMLSelectElement; | |
const container = target.parentNode as HTMLDivElement; | |
if (container) { | |
container.classList.add(this.className); | |
} | |
} | |
private handleBlur = (element: Event): void => { | |
const target = element.target as HTMLInputElement | HTMLSelectElement; | |
const container = target.parentNode as HTMLDivElement; | |
if (container && !target.value) { | |
container.classList.remove(this.className); | |
} | |
} | |
private init = (): void => { | |
this.fields.forEach((element) => { | |
const input = element.querySelector('input') || element.querySelector('select'); | |
if (input && input.value) { | |
element.classList.add(this.className); | |
} | |
this.bindEvents(element); | |
}); | |
} | |
} | |
const floatingLabel = new FloatingLabel({ | |
activeFieldClass: 'floating-label--floating', | |
fieldContainerClass: 'floating-label', | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment