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.
Topics in This Chapter
addEventListener, the function you hand it without calling it, and the event object that tells it what happened.button works for everyone and a clickable div does not, how the Tab key moves focus, and a panel that closes with Escape.