Open original
Info
Demo 3.9

Events

Files in this demo

├─ index.html
└─ script.js

An event is something that happens on the page: a click, a keystroke, a scroll, a form submission. addEventListener lets you run code when one happens.

button.addEventListener("click", function () {
	console.log("clicked!");
});

Three parts: which element, which event, and what to run.

That third argument is a function you’re handing to the browser to keep and call later. It’s normal for it to look a bit strange at first ~ you’re not calling it, you’re giving it away.

Events worth knowing

  • click ~ the obvious one.
  • input ~ fires on every keystroke in a text field.
  • change ~ fires when a field is done being edited.
  • submit ~ on a form.
  • keydown ~ a key was pressed.
  • mouseenter / mouseleave ~ the hover pair, when CSS isn’t enough.
  • scroll, resize ~ on the window.

The event object

Your function gets handed an event object describing what happened:

input.addEventListener("input", (event) => {
	console.log(event.target.value);
});

event.target is the element it happened to. event.preventDefault() stops the browser’s default behaviour ~ that’s how you stop a form reloading the page.

Event delegation

Instead of a listener on every list item, put one on the list:

list.addEventListener("click", (event) => {
	if (event.target.tagName === "LI") { ... }
});

Clicks on the children bubble up to the parent. One listener instead of fifty, and it keeps working for items you add later.

Remembering things

If you need a value to survive between clicks, declare it outside the listener. Inside, it resets every time ~ which is a genuinely confusing first bug.

You finished this book!Start another book
Keyboard Shortcuts
⌘ Z / ⌘ ⇧ ZCtrl Z / Ctrl ⇧ Z Undo / redo
Tab / ⇧ TabTab / ⇧ Tab Indent / unindent selection
⌘ ] / ⌘ [Ctrl ] / Ctrl [ Indent / unindent lines
⌘ ACtrl A Select all
⌘ DCtrl D Select next occurrence of selection
⌘ /Ctrl / Comment / uncomment lines
Ctrl SpaceCtrl Space Autocomplete
Ctrl EnterCtrl Enter Reset layout
⌘ ⌥ [ / ⌘ ⌥ ]Ctrl ⇧ [ / Ctrl ⇧ ] Fold / unfold block
Code
The editor didn't load — try refreshing the page. Navigation, shortcuts and the info panel still work in the meantime.
Preview
Dimensions0 × 0
Delay
Console