Browser events: The `event` object

An event handler gets an Event object as the first parameter, in this example I named it event (you can use any name you want, like e or theevent:

const link = document.getElementById('my-link')
link.addEventListener('click', event => {
  // link clicked
})

This object contains a lot of useful properties and methods, like:

  • target, the DOM element that originated the event
  • type, the type of event
  • stopPropagation(), called to stop propagating the event in the DOM

and more. You can see the full list here.

An event on a DOM element will be propagated to all its parent elements tree unless it’s stopped.

<html>
  <body>
    <section>
      <a id="my-link" ...>

In this example a click event on the element defined with the a tag will propagate to section and then body.

You can stop the propagation by calling the stopPropagation() method of an Event, usually at the end of the event handler:

const link = document.getElementById('my-link')
link.addEventListener('mousedown', event => {
  // process the event
  // ...

  event.stopPropagation()
})

Each specific kind of event, like a mouse click, a touch event, or a keyboard event, implement an event that extends this base Event object.

Lessons in this unit:

0: Introduction
1: Handling events
2: The `DOMContentLoaded` event
3: ▶︎ The `event` object
4: Mouse events
5: Keyboard events
6: `preventDefault()`
7: Stopping event propagation
8: Bubbling and capturing
9: Form submit event
10: Input fields events
11: Creating custom events