What the browser tells your code when something happens, like a click, a tap or a key press.In the glossary
, give the element a function. It runs when the event happens.
import { state } from '@markless/core';export default functionSkipAdfunction SkipAd(): Element() @{@{ · Statement containerHolds instructions: setup lines, then the element to show. letsecondslet seconds: number=statestate · Watched valueDeclares a variable the page watches. You read and assign it like any other variable, and the page keeps up.(5); functionskip(local function) skip(): void() { // every single time 🙄secondslet seconds: number+= 5; } <section<section> · HTML elementA section of a page, usually with its own heading.> <p<p> · HTML elementA paragraph.>Your video starts in {seconds} seconds.</p<p> · HTML elementA paragraph.> <button<button> · HTML elementA button a person can press.onClickonClick · Event handlerRuns when this element gets the DOM event named after on, with the browser's own event object.={skip}>Skip ad</button<button> · HTML elementA button a person can press.> </section<section> · HTML elementA section of a page, usually with its own heading.>}
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.
PlaygroundType @ or < for suggestions · F1 explains a wordRestored your edit·
import { state } from '@markless/core';export default function Lift() @{ let floor = state(0); function go(to: number) {floor = to; } function ground() {floor = 0; } <sectionclass="lift" data-floor={floor}> <divclass="shaft"> <iclass="car" /> </div> <divclass="panel"> <p>Floor {floor === 0 ? 'G' : floor}</p> <buttononClick={() => go(3)}>3</button> <buttononClick={() => go(2)}>2</button> <buttononClick={() => go(1)}>1</button> <buttononClick={ground}>G</button> </div> </section>}
To do: Press 3. go gets 3, the car rides up to the top floor, and the panel reads Floor 3.
To do: Send the G button through go instead: change its onClick to () => go(0).
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.
type any key
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'.
PlaygroundType @ or < for suggestions · F1 explains a wordRestored your edit·
import { element, state } from '@markless/core';import { KEYS, SECRET, rattle } from './safe.ts';export default function Safe() @{ let code = state(''); const door = element<HTMLDivElement>(); function dial(key: string) { if (key === 'Escape') code = ''; if (key === 'Backspace') {code = code.slice(0, -1); } const digit = '0123456789'.includes(key); if (digit && code.length < 3) code += key; if (code.length === 3 && code !== SECRET) {rattle(door, () => (code = '')); } } <sectionclass="safe" tabindex="0"onKeyDown={(event) => dial(event.key)} > <divel={door}class={code === SECRET ? 'open' : 'shut'}style={`--digit: ${code.at(-1) ?? 0}`} > <output>{code}</output> </div> <p>{code === SECRET ? 'Open!' : 'Locked'}</p>@for (const key of KEYS; key key) { <button data-key={key}onClick={() => dial(key)} >{key}</button> } </section>}
export const KEYS = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', 'Escape', '0', 'Backspace',];// The code on the sticky note.export const SECRET = '194';// A wrong code: the door rattles, then resets.export async function rattle( door: HTMLElement | undefined, reset: () => void,) { const shake = { translate: ['0', '-5px', '5px', '-3px', '0'], }; await door?.animate(shake, 350).finished; reset();}
To do: Click the safe and type 1 9 4, the code on the sticky note, or press it on the keypad.
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.
PlaygroundType @ or < for suggestions · F1 explains a wordRestored your edit·
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.
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.
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.PlaygroundType @ or < for suggestions · F1 explains a wordRestored your edit·
import { state } from '@markless/core';export default function Toaster() @{ let name = state(''); <formclass={name ? 'toaster up' : 'toaster'}onSubmit={(event) => { event.preventDefault(); const form = event.currentTarget; const data = new FormData(form); const text = data.get('name'); if (typeof text === 'string') name = text; }} > <divclass="slots"> <b>{name.slice(0, 6)}</b> <i /> <strong>The Deep Toast Co.</strong> </div> <p>It thinks, so you don't have to.</p> <inputname="name" aria-label="Name"value="Robin" /> <button>Join the waitlist</button>@if (name) { <pclass="listed"> Toast for {name} is on the list. </p> } </form>}
.toaster { display: grid; gap: 0.5rem; width: 19rem; max-width: 100%; margin: 0 auto; font-family: 'Shantell Sans', sans-serif;}/* The drawn toaster; the toast sits behind it. */.toaster .slots { position: relative; grid-column: 1 / -1; justify-self: center; width: min(15rem, 100%); aspect-ratio: 160 / 122; margin-top: 2.6rem;}.toaster .slots::after { content: ''; position: absolute; inset: 0; background: center / contain no-repeat url(/examples/ink/events-form-toaster.svg);}/* Your slice on the left, a plain one beside. */.toaster b,.toaster .slots::before { content: ''; position: absolute; top: 9.8%; left: 10%; width: 37.5%; aspect-ratio: 60 / 62; background: center / contain no-repeat url( /examples/ink/events-form-toaster-toast.svg ); transition: translate 0.55s cubic-bezier(0.3, 1.7, 0.5, 1);}.toaster .slots::before { left: 52.5%; transition-delay: 0.06s;}/* Popped, each slice still stands in its slot. */.toaster.up b { translate: 0 -58%;}.toaster.up .slots::before { translate: 0 -48%;}/* The name, burnt in: six letters fit. */.toaster b { display: grid; place-items: center; padding: 0.5rem 0.4rem 0; box-sizing: border-box; color: #6b3a1a; font: 800 0.85rem/1 'Shantell Sans', sans-serif; white-space: nowrap; overflow: hidden; filter: blur(0.3px); opacity: 0.9;}/* Steam off a fresh slice. */.toaster.up b::after { content: ''; position: absolute; bottom: 100%; left: 0; width: 100%; aspect-ratio: 48 / 44; background: center / contain no-repeat url( /examples/ink/events-form-toaster-steam.svg ); animation: steam 2.4s 0.5s ease-out infinite both;}@keyframes steam { from { translate: 0 0.6rem; opacity: 0; } 40% { opacity: 1; } to { translate: 0 -0.6rem; opacity: 0; }}/* The lever: down while toasting, up on a pop. */.toaster i { position: absolute; z-index: 1; top: 65.6%; left: 83.1%; width: 16.25%; aspect-ratio: 26 / 16; background: center / contain no-repeat url( /examples/ink/events-form-toaster-lever.svg ); transition: top 0.25s ease-out;}.toaster.up i { top: 32.8%;}/* The name plate on the front. */.toaster strong { position: absolute; z-index: 1; top: 36%; left: 18.75%; display: grid; place-items: center; width: 62.5%; height: 29.5%; margin: 0; padding: 0 12%; box-sizing: border-box; color: #2d2a24; font-family: inherit; font-size: 0.95rem; line-height: 1.1; text-align: center; text-wrap: balance;}.toaster p { grid-column: 1 / -1; margin: 0; font-size: 0.9rem; text-align: center;}.toaster input,.toaster button { min-width: 0; padding: 0.4em 1em; border: 2px solid; border-radius: 6px; background: none; color: inherit; font: inherit;}.toaster input { padding-inline: 0.6em;}.toaster button { cursor: pointer;}.toaster :is(input, button):focus-visible { outline: 2px dashed currentColor; outline-offset: 2px;}.toaster .listed { padding: 0.2rem 0.6rem; border: 2px dashed; border-radius: 6px;}@media (prefers-reduced-motion: reduce) { .toaster b, .toaster i, .toaster .slots::before { transition: none; } .toaster.up b::after { animation: none; }}
Resize code and preview
Try this
To do: Press Join the waitlist, or type your name and press Enter. The toast pops up with your name burnt in.
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.
PlaygroundType @ or < for suggestions · F1 explains a wordRestored your edit·
import { state } from '@markless/core';export default function Gift() @{ let opened = state(false); let turned = state(false); function unwrap() {opened = !opened; } <sectionclass="gift" onClick={unwrap}> <buttonclass="lid" aria-label="Gift box" aria-expanded={opened} />@if (opened) { <pclass="duck">Too soon!</p> } <buttonclass="tag"onClick={(event) => {turned = !turned; }} >@if (turned) { <b>Not till Sunday!</b> } @else { <b>To Sam, love Gran</b> } </button> </section>}
/* The drawn gift; it shrinks to fit a narrow column. */.gift { position: relative; width: 18rem; max-width: 100%; aspect-ratio: 200 / 244; margin: 0 auto; container-type: inline-size; background: 0 0 / 100% no-repeat url(/examples/ink/events-stop-inside.svg); font-family: 'Shantell Sans', sans-serif; user-select: none; pointer-events: none;}/* Only the box takes a click, not the air round it. */.gift::after { content: ''; position: absolute; top: 48.4%; left: 18%; width: 74%; height: 48.4%; background: center / contain no-repeat url(/examples/ink/events-stop-box.svg); pointer-events: auto; cursor: pointer;}.gift button { position: absolute; z-index: 1; padding: 0; border: 0; background: center / contain no-repeat; color: inherit; font: inherit; pointer-events: auto; cursor: pointer;}.gift button:focus-visible { outline: 2px dashed currentColor; outline-offset: 2px;}.gift .lid { top: 36.1%; left: 16%; width: 78%; height: 27%; background-image: url(/examples/ink/events-stop-lid.svg); transition: translate 0.5s, rotate 0.5s; transition-timing-function: cubic-bezier(0.3, 1.5, 0.6, 1);}.gift .lid:hover { translate: 0 -4%;}/* Open: the lid pops off and hangs in the air. */.gift .lid[aria-expanded='true'] { translate: -4% -114%; rotate: -8deg;}/* The duck rises out of the box, under its front. */.gift .duck { position: absolute; top: 27%; left: 30%; width: 68%; height: 31%; margin: 0; padding: 5cqw 0 0 35cqw; box-sizing: border-box; background: right top / 36cqw no-repeat url(/examples/ink/events-stop-bubble.svg), 3cqw bottom / 29cqw no-repeat url(/examples/ink/events-stop-duck.svg); font-size: 4.6cqw; font-weight: 700; text-align: center; animation: rise 0.6s 0.1s cubic-bezier(0.3, 1.5, 0.6, 1) backwards;}@keyframes rise { from { translate: 0 50%; }}/* The tag hangs from its string by the hole. */.gift .tag { top: 75.6%; left: 53.1%; z-index: 2; width: 32.5%; height: 19.5%; rotate: -6deg; transform-origin: 15% 48%; transition: rotate 0.3s;}.gift .tag:hover { rotate: 4deg;}.gift .tag b { display: grid; place-items: center; height: 100%; padding: 0 2cqw 0 7.5cqw; background: center / contain no-repeat url(/examples/ink/events-stop-tag.svg); font-size: 4.5cqw; line-height: 1.1; animation: turn 0.35s ease-out;}@keyframes turn { from { rotate: y 90deg; }}@media (prefers-reduced-motion: reduce) { .gift .lid, .gift .tag { transition: none; } .gift .duck, .gift .tag b { animation: none; }}
Resize code and preview
Try this
To do: Press the tag to read it. The box opens too.
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.
PlaygroundType @ or < for suggestions · F1 explains a wordRestored your edit·
import { state } from '@markless/core';export default function Well() @{ let woken = state(0); function wake() {woken++; } <sectionclass="well" data-woken={woken}> <divclass="shaft"> <divclass="scene"> <iclass="frog" onVisible={wake} />@if (woken > 0) { <bclass="croak">Ribbit!</b> } </div> </div> <pclass="sign"> <code>wake</code> ran: <b>{woken}</b> </p> </section>}
/* Places on the drawing are % of its size. */.well { font-family: 'Shantell Sans', sans-serif; user-select: none;}/* A short window onto a deep shaft. */.well .shaft { height: 21rem; overflow-y: auto; overscroll-behavior: contain; border-bottom: 2px solid; scrollbar-width: thin; scrollbar-color: color-mix(in oklch, currentColor 16%, transparent) transparent;}.well .scene { position: relative; aspect-ratio: 175 / 575; background: top / 100% no-repeat url(/examples/ink/events-wake-well.svg);}.well .frog { position: absolute; top: 87.3%; left: 31.7%; width: 36.6%; aspect-ratio: 56 / 44; background: center / contain no-repeat url(/examples/ink/events-wake-frog.svg);}/* Awake: open eyes, a hop, a croak. */.well:not([data-woken='0']) .frog { background-image: url(/examples/ink/events-wake-frog-awake.svg); animation: hop 0.5s ease-out;}@keyframes hop { 50% { translate: 0 -1.2rem; }}.well .croak { position: absolute; top: 81.4%; left: 60%; padding: 0.1rem 0.5rem; border: 2px solid; border-radius: 9px 9px 9px 2px; background: #ffd84d; color: #2d2a24; font-size: 0.75rem; rotate: -6deg; animation: hop 0.5s ease-out;}/* The counter under the window. */.well .sign { margin: 0.6rem 0; font-size: 0.9rem; text-align: center;}.well .sign b { display: inline-grid; place-items: center; width: 1.8rem; aspect-ratio: 1; border: 2px solid; border-radius: 50% 45% 55% 48%;}.well:not([data-woken='0']) .sign b { background: #ffd84d; color: #2d2a24;}@media (prefers-reduced-motion: reduce) { .well .frog, .well .croak { animation: none; }}
Resize code and preview
wake ran: 0
Try this
To do: Scroll down the well. wake has run 0 times until the frog comes into view.
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<button> · HTML elementA button a person can press.onIdleonIdle · Idle handlerRuns once, after the page has loaded and the browser is idle.={connectChat}>Chat with us</button<button> · HTML elementA button a person can press.>
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<button> · HTML elementA button a person can press.onClickonClick · Event handlerRuns when this element gets the DOM event named after on, with the browser's own event object.={[send, clearDraft]}>Send</button<button> · HTML elementA button a person can press.>
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<button> · HTML elementA button a person can press.onClickonClick · Event handlerRuns when this element gets the DOM event named after on, with the browser's own event object.={async () => { try { awaitsaveReportimport saveReport(days);noteimport note= 'Saved'; } catch {noteimport note= 'Could not save'; } }}> Save</button<button> · HTML elementA button a person can press.>
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.