Dom Events and Event Handlers in Mithril (using JSX)

DOM events are actions that occur when a user effectively changes the state of the application through interaction with the browser. In order for these changes to occur, event handlers need to be used to manage how the element that was interacted with reacts to a given event. These events come in many forms, including clicks, keystrokes, mouse movements, hovers, and completion or start of different events, among many other things. If there’s an action a user can take, there is most likely an event handler for it (check out more DOM events and their associated event handlers from W3schools).

Writing handlers in Mithril

If you have any experience with events using React, you’ll be well versed in DOM events and event handlers in Mithril. Take a look at this event handler in react:

<button onClick={activateLasers}>  
Activate Lasers
</button>

The same event could be written in Mithril (while using JSX) like so:

<button onclick={activateLasers}>  
Activate Lasers
</button>

That wasn’t a typo. The only major difference is the capitalization of the word directly following the in the event handler. In this particular case, onClick (uppercase) in React is written as onclick (lowercase) in Mithril. This syntax is the same for an onclick in plain old HTML as it is withJSX syntax (except for the lack of curly braces denoting Javascript):

<button onclick="activateLasers()">
Activate Lasers
</button>

Popular Event handlers in action

onclick, executes on the click of a button.

onclick

onmouseover executes every time the mouse is over the top of the element.

onkeypress, onkeyup and onkeydown respectively trigger events when the key is pressed (onkeypress), on the release of the key (onkeyup) and when the user is physically pressing the key down (onkeydown).

onsubmit triggers an event on the submission of a form.

There are plenty of other event handlers to take advantage of but understanding these basic ones is a great place to start.

Budding software engineer based out of Seattle, WA