Course contentsShow
← Web Development
Lesson 723 of 2,98213. DOM EventsFree lesson

stopPropagation() Method

Preventing events from bubbling up or capturing down the DOM tree with stopPropagation().

stopPropagation() Method

What you'll learn: How to prevent events from traveling up or down the DOM tree using stopPropagation().


The Problem: Unwanted Event Propagation

You've already learned that events travel through the DOM tree in two phases: capturing (top-down) and bubbling (bottom-up). Sometimes this behavior causes problems. Imagine clicking a button inside a card — you might trigger both the button's click handler and the card's click handler. If you only want the button to respond, you need to stop the event from propagating.

How stopPropagation() Works

The stopPropagation() method is called on the event object inside your event handler function. It prevents the event from continuing its journey through the DOM tree.

When called during bubbling, it stops the event from traveling up to parent elements. When called during capturing, it stops the event from traveling down to child elements.

Analogy: Think of event propagation like a ripple spreading across water. Calling stopPropagation() is like placing a barrier that prevents the ripple from spreading further.

Syntax Example

const button = document.querySelector('button');
const card = document.querySelector('.card');

button.addEventListener('click', function(event) {
  event.stopPropagation(); // Stop the event here
  console.log('Button clicked');
});

card.addEventListener('click', function() {
  console.log('Card clicked'); // This won't run when button is clicked
});

In this example, clicking the button logs "Button clicked" but not "Card clicked" because we stopped propagation.


Key Takeaway: Use event.stopPropagation() inside an event handler to prevent the event from bubbling up to parent elements or capturing down to child elements, giving you precise control over which handlers execute.