# DOM helpers

Source: https://signy.dev/documentation/1/components/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()

```js
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.

```js
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.

```js
const { Component, Signal, application, html, createRef, DOM, Show } = Signy;

class Menu extends Component {
  open = new Signal(false);
  box = createRef();

  setup() {
    DOM.onClickOutside(() => this.box.current, () => (this.open.value = false));
    DOM.onKeydown(document, "Escape", () => (this.open.value = false));
  }

  render() {
    return html`
      <div ref=${this.box}>
        <button aria-expanded=${() => String(this.open.value)} onClick=${() => this.open.set((o) => !o)}>
          Options
        </button>
        ${Show({
          when: () => this.open.value,
          children: html`
            <ul>
              <li>Rename</li>
              <li>Duplicate</li>
              <li>Delete</li>
            </ul>
          `,
        })}
      </div>
      <p>Open the menu, then click outside it or press Escape.</p>
    `;
  }
}

application(Menu).mount("#dom-dropdown");
```

## Other helpers

- `DOM.query()` and `DOM.queryAll()` find elements, `DOM.getElement()` takes a selector or an element.
- `DOM.addClass()`, `DOM.removeClass()`, `DOM.toggleClass()` and `DOM.hasClass()` change classes.
- `DOM.setAttributes()` and `DOM.removeAttributes()` change several attributes at once.

Each helper is also exported on its own, such as `createClickOutside` for `DOM.onClickOutside`.
