Skip to content
Tutorials Center
My learning

Topics

Lesson 87 of 156 ยท The DOM

Events

Go deeper with addEventListener - the event object, this, removing listeners, once, passive and signal options, keyboard, pointer and custom events.

Events are how a page reacts to the world: a click, a key press, a finger dragging across the screen, a field being edited, the window being resized. The browser fires an event object for each of these, and your listeners decide what to do with it.

The HTML course's lesson on Event Attributes and Event Listeners covered the basics: why addEventListener() beats onclick, the most common events, and event.preventDefault(). This lesson goes further. You will learn how listeners are identified and removed, what this means inside them, the once, passive and signal options, how keyboard and pointer events really work, and how to create events of your own.

Listeners are functions you pass by reference

addEventListener(type, listener, options) registers a function to be called each time an event of that type reaches the element. The listener is a value, not a call:

JavaScript
function handleSave(event) {
  console.log("savingโ€ฆ", event.type);
}

saveButton.addEventListener("click", handleSave);    // correct: pass the function
saveButton.addEventListener("click", handleSave());  // bug: calls it now, passes undefined

Adding the same function for the same event and element twice has no effect; the browser ignores the duplicate. Two different functions, even with identical code, are two separate listeners and both run, in the order they were added.

The event object, in more depth

Every listener receives an event object. Its exact class depends on the event โ€” PointerEvent, KeyboardEvent, InputEvent, SubmitEvent โ€” but all share the basics from Event:

  • type โ€” the event name, like "click".
  • target โ€” the element where the event originated (often a child of the element you listen on).
  • currentTarget โ€” the element whose listener is running right now.
  • timeStamp โ€” when it happened, in milliseconds since the page loaded.
  • isTrusted โ€” true for real user actions, false for events created by scripts.
  • defaultPrevented โ€” whether some listener already called preventDefault().

target versus currentTarget becomes important in the next lesson, when events travel through several elements.

this inside a listener

When the listener is a regular function, this is set to event.currentTarget, the element the listener is attached to. An arrow function has no this of its own, so inside it this is whatever it was in the surrounding code (see The this Keyword).

this and currentTarget

The safest habit is to use event.currentTarget and ignore this in listeners. It works the same with either function style and makes the code easier to read.

Removing listeners

removeEventListener(type, listener) takes a listener off again, but only if you pass the exact same function object (and the same capture setting, if you used one). An anonymous function can never be removed this way, because you have no reference to it:

JavaScript
button.addEventListener("click", () => console.log("hi"));
button.removeEventListener("click", () => console.log("hi")); // no effect: a different function

Store the function in a variable or declare it by name when you will need to remove it.

Listener options: once, passive and signal

The third argument can be an options object:

  • once: true โ€” the listener removes itself after running the first time. Great for "first interaction" logic, intros and one-shot animations.
  • passive: true โ€” a promise that the listener will not call preventDefault(). For touchmove and wheel events this lets the browser start scrolling immediately instead of waiting for your code. (Browsers already treat those listeners on window, document and body as passive by default.)
  • signal: controller.signal โ€” ties the listener to an AbortController. Calling controller.abort() removes every listener registered with that signal, anonymous ones included.
  • capture: true โ€” runs the listener during the capture phase, explained in the next lesson.

The signal option is the modern answer to cleaning up many listeners at once โ€” for example when a dialog or widget is closed. You will see AbortController again in Cancelling with AbortController.

once, removeEventListener and signal

Keyboard events

Keyboard events (keydown and keyup) fire on the element with focus, or on document.body when nothing is focused, and then bubble up. Two properties tell you which key it was:

  • event.key โ€” the character or meaning of the key, respecting the keyboard layout and Shift: "a", "A", "Enter", "ArrowLeft", "Escape", " " for the space bar.
  • event.code โ€” the physical position of the key, ignoring the layout: "KeyA", "Digit1", "Space". A key that types "z" on a German keyboard reports code "KeyY".

Use key for text and shortcuts with a meaning (Enter submits, Escape closes). Use code when position matters, such as WASD movement in a game. Modifier state is available as ctrlKey, shiftKey, altKey and metaKey, and repeat is true while a key is held down.

Keyboard inspector

The old keyCode and which properties, and the keypress event, are deprecated. You will still find them in old answers online; use key, code and keydown instead.

Pointer events

Pointer events unify mouse, pen and touch into one model: pointerdown, pointermove, pointerup, pointerenter, pointerleave and pointercancel. The event's pointerType tells you which device it was, clientX and clientY give the position in the viewport, and offsetX/offsetY the position inside the target. Writing your interactions with pointer events means they work on phones and tablets without separate touch code.

Drawing with pointer events

Two details make this robust. touch-action: none in the CSS stops the browser from scrolling the page while you draw with a finger. setPointerCapture() keeps sending the pointer's events to the canvas even if it leaves the canvas mid-stroke.

Three ways to attach a handler

There are three styles for connecting a function to an event. You will meet all of them in real code, so it helps to know exactly how they differ:

Style Example Several handlers? Notes
Inline attribute <button onclick="save()"> No (one attribute) Code lives in the HTML as a string. this is the element. Blocked by strict Content Security Policies.
Handler property button.onclick = save No: a new assignment replaces the old one Simple, but easy to overwrite by accident. Assign null to remove.
addEventListener() button.addEventListener("click", save) Yes, all run in order Supports options (once, passive, signal, capture) and works for every event type.

Handler attribute and property names are the event name with on in front. These are the ones you'll meet most often:

Handler Fires when
onclick the element is clicked (mouse, touch, or Enter/Space on a button)
onmouseover / onmouseout the pointer moves onto or off the element (or one of its children)
onkeydown / onkeyup a key is pressed down or released
onfocus / onblur the element gains or loses keyboard focus
onchange / oninput a form control's value is committed or changes on every edit
onsubmit a form is submitted
onload a page, image or script has finished loading

With addEventListener() you pass the name without on: "mouseover", "keydown", "blur". Note that mouseover/mouseout also fire when the pointer crosses between child elements; use mouseenter/mouseleave when you only care about the element as a whole.

All three are stored in the same list of handlers for the element, so mixing them is legal, and a property handler keeps the position it had the first time you assigned it. In new code, use addEventListener(); use the others only when you read old code or need a quick throwaway demo.

The next editor puts all three on one button and then shows the difference between focus/blur and their bubbling cousins focusin/focusout. Click the buttons and tab through the text fields, and watch the console.

Handler styles and focus events

Mouse and wheel events

Pointer events (above) are the best choice for new interaction code, but you will still see the older mouse events, and a few of them have no pointer twin:

  • click, dblclick and contextmenu (the right-click menu; call preventDefault() to supply your own).
  • mouseenter and mouseleave fire once when the pointer enters or leaves the element and do not bubble. mouseover and mouseout bubble and also fire when the pointer moves between the element's own children, which makes hover effects flicker if you are not careful. Prefer mouseenter/mouseleave, or CSS :hover.
  • wheel reports the mouse wheel or trackpad scroll. Read event.deltaY (positive means scrolling down) and event.deltaMode (pixels, lines or pages). To stop the page from scrolling, you must call preventDefault() in a listener registered with { passive: false }, because wheel listeners on the page are passive by default.

Use wheel to build things like a zoomable image or a custom carousel, but keep the page's normal scrolling working for everyone else; hijacking the wheel everywhere is a well-known annoyance.

Window and document events

Some events belong to the page as a whole:

  • DOMContentLoaded fires on document when the HTML has been parsed and deferred scripts have run, without waiting for images, stylesheets or iframes. It is the right moment to start wiring up the page. A script loaded with defer or as a module already runs at about this time.
  • load fires on window when everything, including images and styles, has finished loading. Use it only when you need final sizes of images.
  • resize fires on window when the viewport changes size. It can fire many times per second while a user drags the window edge. Read the size (innerWidth) and do the minimum, or use ResizeObserver for an individual element (see Observers).
  • scroll fires on the scrolled element (or document for the page), not on every ancestor, because it does not bubble. Register it with { passive: true } and batch visual updates with requestAnimationFrame.
  • beforeunload lets you ask "Leave site?" when a form has unsaved changes. Browsers only show their own generic message, and only if the user has interacted with the page.
Loading order, scrolling and the wheel

In the console, readyState is "loading" when the script runs, then DOMContentLoaded is logged, then load. If the wheel listener were passive, the preventDefault() call would be ignored (the browser prints a warning) and the page would still scroll.

Other events worth knowing

  • Focus: focus and blur fire on the element itself and don't bubble; focusin and focusout are the bubbling versions.
  • Forms: input, change, submit, reset and invalid (all in Working with Forms).
  • Page: DOMContentLoaded on document; load, resize, scroll, beforeunload and online/offline on window.
  • Visibility: visibilitychange on document fires when the user switches tabs; check document.visibilityState to pause work in hidden tabs.
  • Clipboard and drag: copy, paste, dragstart, drop (see Drag and Drop).

scroll and pointermove can fire dozens of times per second. Keep their listeners light, and use the debounce and throttle techniques for expensive work.

Custom events

You can create and fire your own events with new CustomEvent(type, options) and element.dispatchEvent(event). The detail option carries any data you like. This lets parts of your page communicate without knowing about each other: a cart component announces "item added", and a header badge listens for it.

JavaScript
cart.dispatchEvent(new CustomEvent("cart:add", {
  detail: { sku: "TEA-01", qty: 2 },
  bubbles: true,           // custom events don't bubble unless you ask
}));

document.addEventListener("cart:add", (event) => {
  console.log(event.detail.sku);
});

dispatchEvent() runs listeners synchronously, before it returns, and the events it creates have isTrusted set to false. If you just want to simulate a real click on a button, button.click() fires a click event and also triggers the button's default action.

Cancelable and bubbling custom events

A CustomEvent is a normal event with an extra detail property. Its options are the same as for built-in events:

  • detail carries any data. Pass a plain object, and treat it as read-only for the listeners.
  • bubbles: true makes the event travel up the DOM tree, so one listener on a parent or on document can hear it from any child. The default is false.
  • cancelable: true lets listeners call preventDefault(). dispatchEvent() then returns false, so the code that fires the event can ask "does anyone object?" before it goes ahead.

Naming matters: custom event names are free-form strings, and a prefix such as cart:add keeps them from colliding with built-in events.

Custom events that bubble through the page

The list and the badge never reference each other. You could move either to another part of the page, or add a third listener that saves the cart, without touching the code that fires the event. That loose coupling is the main reason to use custom events.

Events without a DOM: EventTarget and emitters

Events are not limited to elements. EventTarget is the small base class behind them, and you can create one directly or extend it in your own class. Because EventTarget, Event and CustomEvent also exist in Node.js and in workers, code written this way runs in many places. The editor below uses only these classes, so it needs no page at all:

JS EventTarget, subclasses and cancelable events

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Everything you learned about listeners applies: once, signal and removeEventListener all work on your own EventTargets. One difference from DOM events is that a plain EventTarget has no parent, so nothing bubbles.

The emitter pattern

Many libraries (Node.js's EventEmitter, mitt, Vue's event bus) use a smaller pattern called an emitter or publish/subscribe: an object keeps a list of functions per event name, on() adds one, off() removes it, and emit() calls them all. It is easy to write yourself, and the version below returns an unsubscribe function from on(), which saves you from keeping a reference to the handler just to remove it:

JS A small event emitter

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Which should you choose? For anything tied to the DOM, use real events and CustomEvent; they bubble, they work with the same tools as every other event, and other developers know them. For logic that lives outside the DOM, an EventTarget subclass gives you the standard API for free, while a hand-written emitter is handy when you want on() to return an unsubscribe function or you need the call order and arguments to be completely under your control.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why doesn't this remove the listener? btn.removeEventListener("click", () => go())

    Removal needs the exact same function reference. Keep the listener in a variable, or use { signal } with an AbortController.
  2. 2. A user on a French AZERTY keyboard presses the key that types "a". What is event.code?

    code names the physical key as if on a US QWERTY layout. On AZERTY, "a" sits where QWERTY has Q. event.key would be "a".
  3. 3. What does { once: true } do?

    The listener is removed right after its first call.
  4. 4. Inside a listener written as an arrow function, which expression reliably gives the element the listener is attached to?

    Arrow functions don't get their own this. event.currentTarget is always the element whose listener is running; event.target may be a descendant.
  5. 5. Why use pointer events like pointerdown instead of mousedown?

    Pointer events unify all pointing devices, and pointerType tells you which one fired.

Summary

  • Pass listeners as function references; the same function added twice is ignored, different functions all run in order.
  • The event object carries type, target, currentTarget, isTrusted and more; prefer event.currentTarget over this.
  • removeEventListener() needs the identical function; { signal } with an AbortController removes many listeners at once.
  • { once: true } runs a listener a single time; { passive: true } promises not to call preventDefault() so scrolling stays smooth.
  • Use event.key for meaning and event.code for physical position; use pointer events for mouse, pen and touch together.
  • Inline attributes, handler properties (onclick, one at a time) and addEventListener() (many, with options) can all attach handlers; prefer addEventListener().
  • focus/blur and mouseenter/mouseleave do not bubble (use focusin/focusout or capture); wheel needs { passive: false } before preventDefault() works; DOMContentLoaded comes before load.
  • CustomEvent with detail and dispatchEvent() lets components talk through events; add bubbles to reach ancestors and cancelable to let listeners veto.
  • Extend EventTarget for events outside the DOM, or write a small emitter whose on() returns an unsubscribe function.

Next: Bubbling, Capturing and Delegation โ€” how events travel through the tree and how one listener can handle many elements.