Events

8 min·Assumes: state

To react to clicks, key presses and other browser
, give the element a function. It runs when the event happens.
import { state } from '@markless/core';

export default function SkipAd() @{
	let seconds = state(5);

	function skip() {
		// every single time 🙄
		seconds += 5;
	}

	<section>
		<p>Your video starts in {seconds} seconds.</p>
		<button onClick={skip}>Skip ad</button>
	</section>
}

onClick is on plus the browser's click event. The button is given a function, and it runs each time the button is pressed, never before. Every DOM event works this way: onKeyDown, onInput, onPointerMove, onFocus.

Pass your own values

To pass a value, wrap the call in an arrow function: onClick={() => go(3)}. A function that needs no value can be given by name, as ground is here.

PlaygroundRestored your edit

Floor G

Try this
  1. To do: Press 3. go gets 3, the car rides up to the top floor, and the panel reads Floor 3.
  2. To do: Send the G button through go instead: change its onClick to () => go(0).
  3. To do: Try breaking it: take the arrow off one button, onClick={go(2)}. The build stops, because that runs go once while the page is set up and gives onClick its result instead of a function.

Your function gets the browser's event

Your function is handed the browser's own event object, so every property and method you know from JavaScript works: event.key, event.target, event.preventDefault().

Press a key on the drawing, or type on your own keyboard.

eventkey: "a"a
An ink drawing of one keyboard key and an empty open hand, with a faint pencil sketch of a card arcing from the key into the hand. Press the key, or focus it and type any key on your own keyboard: the key sinks, and a card labelled event slides out to land in the hand, reading which key it was. With no press, no card arrives. Escape on the focused key empties the hand.

Read the key with event.key

event.key is the name of the key that was pressed: 'Enter', 'Escape', 'a', '1'.

PlaygroundRestored your edit

Locked

Try this
  1. To do: Click the safe and type 1 9 4, the code on the sticky note, or press it on the keypad.
  2. To do: Let Enter shut it again: inside dial, add if (key === 'Enter') code = '';.

Read what was typed or chosen

Give a control its value from state, and write the new value back in your function. The new value is on the element itself, which is event.currentTarget:

  • Text box, text area: onInput, then event.currentTarget.value.
  • Number, range: onInput, then event.currentTarget.valueAsNumber.
  • Select: onChange, then event.currentTarget.value.
  • Checkbox: onChange, then event.currentTarget.checked.
  • Radio: onChange, and set the value that radio stands for.
PlaygroundRestored your edit
Try this
  1. To do: Drag Wind right, tick Rain and choose Night. The tree bends, rain falls and the moon comes up. Then press Fair weather: every control jumps back with the sky.
  2. To do: Add a Storm button that sets wind = 50 and rain = true.

event.target is different: it is whatever was actually pressed, which can be something inside the element.

Stop what the browser would do

Submitting a form loads a new page unless your onSubmit function calls event.preventDefault(). With the page kept, new FormData(event.currentTarget) reads each field by its name.

example.com/joinEmailada@example.comJoinJoinedevent.preventDefault()on
An ink drawing of a browser window with a sign-up form: an email box, a Join button and a list of who joined. Beside it is a switch labelled event.preventDefault(). With the switch on, Join adds the email to the list and the page stays. With it off, Join spins the reload arrow, the page reloads, and the typed email and the list are gone. Press the email box to type a sample email.

PlaygroundRestored your edit
The Deep Toast Co.

It thinks, so you don't have to.

Try this
  1. To do: Press Join the waitlist, or type your name and press Enter. The toast pops up with your name burnt in.
  2. To do: The form finds the field by its name. Rename the input to name="guest", change data.get('name') to match, and press Join the waitlist again.

Stop a click reaching the parent

A click on the tag also reaches the box it hangs on, so both functions run. Call event.stopPropagation() in the tag's function to keep the click on the tag.

PlaygroundRestored your edit
Try this
  1. To do: Press the tag to read it. The box opens too.
  2. To do: Add event.stopPropagation(); above turned = !turned;. Now only the tag turns.

There is no shortcut like onClick|once. You write the call, as in plain JavaScript.

Events that happen by themselves

onVisible and onIdle are given a function like onClick, but no person starts them. onVisible runs it the first time the element scrolls into view.

PlaygroundRestored your edit

wake ran: 0

Try this
  1. To do: Scroll down the well. wake has run 0 times until the frog comes into view.
  2. To do: Scroll up and down again. It stays at 1: onVisible runs once. Then swap it for onClick={wake}, and the frog sleeps until you press it.

onIdle runs your function once the page has loaded and the browser has nothing else to do. Use it for work nobody has asked for yet, like loading a chat widget, so it never slows down the first look or the first press:

<button onIdle={connectChat}>Chat with us</button>

Your function's code waits for its event

Your component runs once, to set up the page. The functions you give to events aren't part of that: each one runs only when its event happens.

Can one event run several functions?

Pass an array, and they run in order. If one throws an error, the ones after it don't run.

<button onClick={[send, clearDraft]}>Send</button>
What if my function awaits something and it fails?

Your function can be async. If something it awaits fails, catch the error and keep a message in state:

<button
	onClick={async () => {
		try {
			await saveReport(days);
			note = 'Saved';
		} catch {
			note = 'Could not save';
		}
	}}
>
	Save
</button>

If you don't catch it, your function stops at that await and the browser reports an uncaught error. The Async page shows another way, where the error shows in a @catch around the element.

Computed values work a value out from your state, so it can never go stale.