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
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.
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:
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
| Category | Events |
|---|---|
| Mouse / pointer | click, dblclick, pointerdown, pointerup, pointermove, mouseenter, mouseleave, contextmenu |
| Keyboard | keydown, keyup |
| Forms | input, change, submit, focus, blur, reset |
| Page / window | DOMContentLoaded, load, resize, scroll, beforeunload, visibilitychange |
| Media and other | play, 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
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
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:
Removing listeners and options
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:
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" } }));