Can anyone please tell me difference in usage of cancelBubble
and stopPropagation
methods used in Javascript.
preventDefault() prevents the default browser behavior for a given element. stopPropagation() stops an event from bubbling or propagating up the DOM tree. Whereas, return false is a combination of both preventDefault() and stopPropagation() .
stopPropagation() The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed.
In short: event. stopPropagation() allows other handlers on the same element to be executed, while event. stopImmediatePropagation() prevents every event from running.
The cancelBubble() method prevents the event-flow from bubbling up to parent elements. Tip: To prevent both bubbling up to parent elements and capturing down to child elements, use the stopPropagation() method instead.
cancelBubble
is an IE-only Boolean property (not method) that serves the same purpose as the stopPropagation()
method of other browsers, which is to prevent the event from moving to its next target (known as "bubbling" when the event is travelling from inner to outer elements, which is the only way an event travels in IE < 9). IE 9 now supports stopPropagation()
so cancelBubble
will eventually become obsolete. In the meantime, the following is a cross-browser function to stop an event propagating:
function stopPropagation(evt) { if (typeof evt.stopPropagation == "function") { evt.stopPropagation(); } else { evt.cancelBubble = true; } }
In an event handler function, you could use it as follows:
document.getElementById("foo").onclick = function(evt) { evt = evt || window.event; // For IE stopPropagation(evt); };
For compatibility with IE8 and older use .cancelBubble
if .stopPropogation()
is undefined:
if(ev.stopPropagation)ev.stopPropagation(); else ev.cancelBubble=true; // where ev is an event object
Read about in MSDN: http://msdn.microsoft.com/en-us/library/ff975961%28v=vs.85%29.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With