Chapter Nine · Behaviour

Events: Answering the User

How a page answers its visitor: listeners that run when something happens, events that bubble up so one listener can serve many elements, controls that work from the keyboard as well as the mouse, and a choice remembered between visits.

The last chapter's scripts ran once, as the page loaded, and then stopped. A page that answers people needs code that waits: for a click, a key, a change in a field. The browser supplies the waiting. Each time something happens it creates an event, and your script only has to say which function should run when it does. This chapter is where the site starts to respond, and where it learns to respond to everyone, not only to people with a mouse.

Four topics. The first attaches listeners and reads the event object they receive. The second follows an event as it bubbles up the tree, and uses that to give the Projects page a filter run by a single listener. The third shows why a real button works for keyboard and screen-reader users and a clickable box does not, and how focus moves. The fourth stores a choice in the browser, so the site remembers each visitor's light or dark theme.

The loop behind every interaction
Something happensa click, a key
→
The browser creates an eventtype, target, key
→
Your listener runson that element or an ancestor
→
The page changesand the visitor sees it

Topics in This Chapter