Search⌘ K
AI Features

Go farther with Events

Explore event propagation in the DOM and learn to control it by stopping propagation and preventing default behaviors in JavaScript. This lesson helps you handle events precisely by managing how they bubble up through the DOM and how to override default browser actions.

Event propagation

The DOM represents a web page as a hierarchy of nodes. Events triggered on a child node are going to get triggered on the parent node, then the parent node of the parent node, up until the root of the DOM (the document variable). This is called event propagation. To see propagation in action, use this HTML code to create a small DOM hierarchy.

Here’s the complementary JavaScript code. It adds click event handlers on the button, its parent (the paragraph), and the parent of that too (the root of the DOM).

The result in the browser console demonstrates the propagation of click events from the button up to the document level. You clicked the button, which means you also clicked the paragraph, which means you also clicked the document.

But maybe you only want an event to kick off once the button is clicked and not count its larger ecosystem? Event propagation can be interrupted at any moment by calling the stopPropagation() method on the Event object from an event handler. This is useful to avoid the same event being handled multiple times.

Adding a line in the button’s click handler prevents the click event from propagating everywhere in the DOM tree.

Cancelling the default behavior of an action

Most of the user actions on a page are associated to a default behavior. Clicking on a link navigates to the link target, clicking anywhere with the right mouse button show a contextual menu, etc. Cancelling a default behavior is possible by calling the preventDefault() method on the Event object in an event handler.

Let’s use the following HTML and JavaScript code to see this possibility in action

Now clicking on the links shows a dialog instead of navigating to its target.