Events

Events are how a page reacts to the world: clicks, key presses, typing, scrolling, a form being submitted, an image finishing loading. You attach a listener — a function — to an element, and the browser calls it every time that event happens.

addEventListener

Try it yourself
Result

The pattern never changes: select an element, call addEventListener(type, handler). An element can have many listeners for the same event; they run in the order they were added.

Avoid inline handlers. Older code uses onclick="…" attributes in HTML or el.onclick = fn. Attributes mix behaviour into markup, and the property form allows only one handler per event. addEventListener is the standard approach.

The event object

Every listener receives an event object describing what happened:

Try it yourself
Result

Useful properties include type, target (the element that was actually clicked), currentTarget (the element the listener is on), mouse coordinates, and modifier keys (shiftKey, ctrlKey, altKey, metaKey).

Common event types

CategoryEvents
Mouse / pointerclick, dblclick, pointerdown, pointerup, pointermove, mouseenter, mouseleave, contextmenu
Keyboardkeydown, keyup
Formsinput, change, submit, focus, blur, reset
Page / windowDOMContentLoaded, load, resize, scroll, beforeunload, visibilitychange
Media and otherplay, ended, animationend, transitionend

Pointer events (pointerdown etc.) work for mouse, touch and pen alike, so they're preferred over separate mouse and touch events for new code.

Keyboard events

Try it yourself
Result

event.key is the character or key name ("a", "Enter", "ArrowUp"); event.code is the physical key position ("KeyA"), regardless of keyboard layout.

Input and change

Try it yourself
Result

input fires on every change as the user types or drags; change fires once the user commits a value (leaves the field, picks an option).

Preventing default behaviour

Many events have a built-in browser action: links navigate, forms reload the page, right-click opens a menu. event.preventDefault() cancels it so your code can handle things instead:

Try it yourself
Result

Removing listeners and options

Try it yourself
Result

removeEventListener needs the same function reference that was added, so use a named function, not an inline arrow. Useful options: { once: true } removes the listener after one call, and { passive: true } promises not to call preventDefault, which makes scroll and touch listeners smoother.

Custom events

You can create and dispatch your own events to let parts of a page communicate:

JS custom.js
const cart = document.querySelector("#cart");
cart.addEventListener("item-added", e => console.log("Added:", e.detail.name));
cart.dispatchEvent(new CustomEvent("item-added", { detail: { name: "Lamp" } }));

Try it yourself

Try it yourself
Result