DOM elements can be nested inside each other. And the handler of the parent works even if you click on it’s child. The reason is event bubbling.
The main principle of bubbling states:
After an event triggers on the deepest possible element, it then triggers on parents in nesting order.
Live Demo for event Bubbling with code
JSFiddle | https://jsfiddle.net/anshul24mehta/wgezytdb/
The bubbling goes right to the top from bottom when event occur. You can stop same by using below code:
event.stopPropagation ? event.stopPropagation() : (event.cancelBubble=true)
Hint: above code is cross-browser compatible
Note: If the element has several handlers on same event, then handlers are independent. All of them get executed.
The main principle of capturing states:
After an event triggers on the parent possible element, it then triggers on its child elements in nesting order.
capturing is Top to bottom approach for event propagation.
In all browsers, except IE<9, there are two stages of event processing.
The event first goes down - that’s called capturing, and then bubbles up. This behavior is standardized in W3C specification.
So in nutshell the event:
addEventListener
with last argument true
, which is the only way to catch the event on capturing stage.event.cancelBubble=true
(IE) orevent.stopPropagation()
for other browsers.