Web Analytics

Event Listeners

Intermediate ~20 min read

The addEventListener() Method

The addEventListener() method attaches an event handler to an element without overwriting existing event handlers.

element.addEventListener(event, function, useCapture);
HTML
CSS
JS

The Event Object

When an event occurs, the browser creates an event object, puts details into it, and passes it as an argument to the handler.

HTML
CSS
JS

Event Bubbling vs Capturing

There are two ways of event propagation in the HTML DOM: bubbling and capturing.

  • Bubbling (Default): The inner element's event is handled first, then the outer.
  • Capturing: The outer element's event is handled first, then the inner.
HTML
CSS
JS

Removing Listeners

The removeEventListener() method removes event handlers that have been attached with the addEventListener() method.

Note: To remove a handler, the handler function must be a named function (not an anonymous function).

HTML
CSS
JS

Summary

  • Use addEventListener to attach multiple handlers to an element.
  • The event object contains information about the event.
  • Event bubbling handles inner elements first; capturing handles outer elements first.
  • Use removeEventListener to clean up event handlers.

Quick Quiz

Which method stops the event from bubbling up the DOM tree?

A
event.stop()
B
event.preventDefault()
C
event.stopPropagation()
D
event.cancelBubble()