Event Handling

Event handling remains close to the native way but enhanced with active listeners instead. Think about it more like an inline addEventListener instead event attributes.

const handleClick = (evt: Event) => {
  evt.preventDefault();
  evt.stopPropagation();
}


html`<button onclick="${handleClick}">click me</button>`
// renders: <button>click me</button>`

The inline event attributes are removed during parsing before the DOM element is created and will never show on the page.

All event attributes must start with on keyword followed by the name of the event. This is nothing specific to this library but something native to HTML itself.

The value of this attribute must be a function of any type.

Custom events

You may also listen to custom events just like you would with native ones. The pattern remains the same and you get a CustomEvent instead of an Event instance.

const handleClick = (evt: CustomEvent) => {
  // handle here
}


html`<my-button onclicked="${handleClick}">click me</my-button>`
// renders: <button>click me</button>`

This is particularly good when working with web components.

Event options

One thing that you cannot do natively in HTML, but you can with Markup is providing event listener options.

const handleClick = (evt) => {
  // will only get called once
}

html`<button onclick="${handleClick}, ${{once: true}}">click me</button>`
// renders: <button>click me</button>

All you need to do is add a comma followed by the option you want to provide to the listener.