An event propagates or bubbles till the window object-level every time a registered event is called. For example, Let us consider a parent div element (“Div Parent”) that contains another child div element (“Div child”), and for both, a click event is registered. If child div is clicked, the event will be fired at all places i.e, at both parent and child objects.
StopPropagation() event method: Prevents propagation of any handlers at top-level DOM hierarchy to execute. It stops the click event from bubbling to the parent elements.
Example: In this method, after clicking the <div> element 1st event handler will occur after that nothing will happen. If you click the <p> element then the 2nd and 1st event handler will occur because <p> element is inside of <div> element but if you click <span> element only the 3rd event handler will occur, cause StopPropagation() event method stops the event from bubbling to the parent elements.
- Before Clicking the element:
- After Clicking the <div> element:
- After Clicking the <p> element:
- After Clicking the <span> element:
StopImmediatePropagation() event method: Prevents both propagation of any other handlers and those at top level DOM hierarchy. It stops the other events which were assigned after this event.
Example: The StopImmediatePropagation() event stops the next event.
- Before Clicking the div element:
- After clicking the div element:
stopPropagation vs stopImmediatePropagation
|It will allow other handlers on the same element to be executed, prevent handlers on parent elements from running.||It will prevents every event from running.|
|It will allow more than one handeler to be executed one by one.||It will depend on you where you used this, that handeler will be the last one to be executed.|
|If you create a table containing <table>, <tr> and <td>. If you set three event handeler for <td> then other two event handeler will also run with this one.||But in this case if you do the same things the other two event handelers won’t run.|