Skip to content
Advertisement

What’s the right mindset in using jQuery’s event.stopPropagation()

I have two approaches in mind on how to apply jQuery’s event.stopPropagation():

  1. Optimistic approach – By default, all event handlers are without stopPropagation(). stopPropagation() would be added to a handler only if there’s some unnecessary and undesired behaviour caused by event bubbling.
  2. Pessimistic approach – By default, stopPropagation() is added to all event handlers. If there’s some desired behaviour missing due to disconnected even bubbling, then the corresponding stopPropagation() would get removed.

I was wondering which one of the two, or neither, is the mindset I should have when utilizing stopPropagation() in my development. I am leaning more towards 2) because it looks like it would have better performance because unnecessary bubbling gets prevented. I would like to hear from experts on the topic.

Advertisement

Answer

Calling stopPropagation everywhere isn’t good. It breaks event delegation*, is probably less efficient unless you literally add handlers to every single element on the page (and if you’re doing that, you should be using event delegation), and you might not remember to do it.

So rule of thumb: Only call stopPropagation when you need to do so.


* That is, .live, .delegate, and the delegate version of .on.


Here’s an example of event delegation, which relies on bubbling to listen for events that originate from elements added after the listener was created:

document.documentElement.addEventListener('click', function(e) {
    if(e.target.nodeName === 'a') {
        console.log('A link was clicked!');
    }
});

Here’s somebody throwing in jQuery that breaks that:

$('div').click(function(e) {
    e.stopPropagation();
});

Any <a> that is a descendant of a <div> will no longer get its clicks handled! Please don’t do this.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement