Event Handlers

Edit this page

Event handlers are functions that are called in response to a specific event occurring in the browser, such as when a user clicks or taps on an element. To add an event handler to an element, you can use the on prefix followed by the event name, and assign it a function.

<button onClick={handleClick}>Click me</button>

When using event handlers in Solid, they can be written using camelCase or all lowercase.

<button onclick={handleClick}>Click me</button>

Event delegation

Instead of attaching event listeners to every individual element, Solid uses artificial event delegation. This means that event listeners are attached to the root element and events are captured as they bubble up.

By keeping the number of event listeners to a minimum, events can be captured more effectively. This is especially useful when working with large lists of elements, such as in a table or list.

Supported events such as click, mouseover, and keydown are just a few examples that are optimized in this way. To view the full list see the references below.

If you need to attach an event listener to an element that is not supported by Solid's event delegation, you can use the on: prefix followed by the event name, and assign it a function.

<div on:customEvent={handleCustomEvent} />

Binding events

In Solid, event handlers can be bound by passing an array to the event handler. The second item of the array is supplied as the handler's first argument.

const handler = (data, event) => {
console.log("Data:", data, "Event:", event);
<button onClick={[handler, "Hello!"]}>Click Me</button>;

In this example, the string 'Hello!' (the second item in the array) is passed as the data parameter (the first argument of the handler function) when the button is clicked.

By binding events in this way, the overhead of using JavaScript's bind method is avoided.

Delegated Events

You can also view this list in our source code (see DelegatedEvents).

Report an issue with this page