@randstad-design/orbit-multitheme
Version:
multitheme Front-end code based on Randstad Human Forward components
77 lines (67 loc) • 1.73 kB
JavaScript
/**
* clearable.js
* Script adds a button to input field, to clear input
*/
import ElementHelpers from '../helpers/element-helpers';
/**
* Declare constants
*/
const attributeBase = 'data-rs-clearable';
export class Clearable {
constructor(element) {
this.element = element;
this.input = this.element.querySelector('input');
this.button = ElementHelpers.getElementByAttributeWithinElement(this.element, this.attributes.button);
if (this.input) {
if (this.input.value && this.input.value.length > 0) {
this.element.classList.add(this.classes.clearableInputActive);
}
this.addEventHandlers();
}
}
/**
* Declare attribute constants
*/
get attributes() {
return {
button: `${attributeBase}-button`,
ariaHidden: 'aria-hidden'
}
}
/**
* Declare classes
*/
get classes() {
return {
clearableInputActive: 'clearable-input--active'
}
}
/**
* Add event handlers
*/
addEventHandlers() {
this.button.addEventListener('click', (event) => {
event.preventDefault();
this.input.value = '';
this.element.classList.remove(this.classes.clearableInputActive);
ElementHelpers.triggerEvent(this.input, 'change');
this.button.setAttribute(this.attributes.ariaHidden, true);
this.input.focus();
});
this.input.addEventListener('input', () => {
if (this.input.value.length > 0) {
this.element.classList.add(this.classes.clearableInputActive);
this.button.setAttribute(this.attributes.ariaHidden, false);
} else {
this.element.classList.remove(this.classes.clearableInputActive);
this.button.setAttribute(this.attributes.ariaHidden, true);
}
});
}
/**
* Get selector
*/
static getSelector() {
return `[${attributeBase}]`;
}
}