Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between cancelBubble and stopPropagation?

Can anyone please tell me difference in usage of cancelBubble and stopPropagation methods used in Javascript.

like image 219
ahamed Avatar asked Sep 29 '11 11:09

ahamed


People also ask

What is the difference between e preventDefault and e stopPropagation?

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() .

What is 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.

What is the difference between event stopPropagation and event stopImmediatePropagation?

In short: event. stopPropagation() allows other handlers on the same element to be executed, while event. stopImmediatePropagation() prevents every event from running.

What is cancelBubble?

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.


2 Answers

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); }; 
like image 89
Tim Down Avatar answered Oct 05 '22 23:10

Tim Down


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

like image 40
Andrew D. Avatar answered Oct 06 '22 00:10

Andrew D.