Stopping event bubbling in JavaScript

Event bubbling can be stopped on any element through which the event is bubbling. To do this, call the stopPropagation method of the Event object in the element code.

In the following example, clicking on the red block will work on itself, then on the blue block and that's it - the blue block stops further bubbling and the green block will not react in any way:

elem1.addEventListener('click', function() { console.log('green'); }); elem2.addEventListener('click', function(event) { console.log('blue'); event.stopPropagation(); // stops the propagation }); elem3.addEventListener('click', function() { console.log('red'); });

You can check: