DOM helpers
Listeners on window, document or any element, removed for you.
Events on elements inside a template use onClick and
friends. For targets outside it, such as window,
document or a click anywhere on the page, use the
DOM helpers. Called in setup(), the listener
belongs to the component and is removed when it unmounts.
DOM.on()
protected setup(): void {
DOM.on(window, 'resize', () => (this.width.value = innerWidth));
}
It takes a target, an event name, a handler and the usual listener options, and returns a function that removes the listener early. The target can be a function, such as one that returns a ref's element. The listener then moves when the function returns another element.
DOM.onKeydown()
A keydown listener for one key or a list of keys, with optional modifiers.
DOM.onKeydown(document, 'Escape', () => this.close());
DOM.onKeydown(document, ['z', 'Z'], () => this.undo(), { ctrl: true, shift: false });
ctrl, alt, shift and
meta must match when set and are ignored when left out.
DOM.onClickOutside()
Runs the handler on a click anywhere except on the element or inside it.
Other helpers
DOM.query()andDOM.queryAll()find elements,DOM.getElement()takes a selector or an element.DOM.addClass(),DOM.removeClass(),DOM.toggleClass()andDOM.hasClass()change classes.DOM.setAttributes()andDOM.removeAttributes()change several attributes at once.
Each helper is also exported on its own, such as createClickOutside for DOM.onClickOutside.