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

event.stopPropagation(): Halting Event Flow

Stopping an event from bubbling up or capturing down through the DOM tree.

event.stopPropagation(): Halting Event Flow

You'll learn how to prevent an event from continuing its journey through the DOM tree.

What Is stopPropagation?

When an event fires on an element, it doesn't just stay there—it travels through the DOM tree during the capturing and bubbling phases. Sometimes you want to stop this journey early. The stopPropagation() method does exactly that: it prevents the event from moving to the next element in the chain.

Think of it like stopping a rumor from spreading. Imagine someone whispers something to you, and normally you'd pass it along to others in the room. Calling stopPropagation() is like deciding, "I heard this, but I'm not passing it on to anyone else."

When and Why to Use It

You typically use stopPropagation() when:

  • A child element handles an event and you don't want parent elements to react
  • Nested clickable elements would otherwise trigger multiple handlers
  • You want fine-grained control over which handlers execute

How It Works

const childButton = document.querySelector('.child-button');
const parentDiv = document.querySelector('.parent-div');

childButton.addEventListener('click', (event) => {
  console.log('Child clicked!');
  event.stopPropagation(); // Event stops here
});

parentDiv.addEventListener('click', () => {
  console.log('Parent clicked!'); // This won't run when child is clicked
});

Without stopPropagation(), clicking the child button would log both messages (bubbling behavior). With it, only the child's handler executes—the event never reaches the parent.

Important Distinction

Remember: stopPropagation() stops the event from traveling to other elements, but it doesn't prevent the default browser action. That's what preventDefault() is for (which you learned previously).

Key Takeaway: event.stopPropagation() halts an event's journey through the DOM tree, preventing parent or child elements from receiving the event during bubbling or capturing.