Javascript : How to enable stopPropagation?

Adam Halasz picture Adam Halasz · Jan 19, 2011 · Viewed 49.2k times · Source

With object.stopPropagation() I can stop event bubbling but how can I re-enable it?

Is there a pre defined function in js something like object.startPropagation?

EDIT:

The Problem is that the JS remembers if you click on the "object" than stop Event Bubbling always even after I don't want it, so I would like to stop it:

document.getElementById("object").onclick = function(e){
    if(e && e.stopPropagation) {
        e.stopPropagation();
    } else {
          e = window.event;
          e.cancelBubble = true;
    }
}

Answer

djdd87 picture djdd87 · Jan 19, 2011

It doesn't remember the value at all. The event e is new each time onclick is fired. The problem is you're always cancelling the event bubbling:

if(foo) {
    e.stopPropagation();
} else {
    e.cancelBubble = true;
}
  • e.stopPropagation is the W3C method of preventing event bubbling.
  • e.cancelBubble is the Microsoft method to prevent event bubbling.

They're both the same. So you're cancelling bubbling of events every time. More reading here.

You'll need to change your method so that it only cancels bubbling if your criteria are met:

document.getElementById("object").onclick = function(e) {

    if(e && e.stopPropagation && someCriteriaToStopBubbling === true) 
    {
        e.stopPropagation();
    } 
    else if (someCriteriaToStopBubbling === true)
    {
          e = window.event;
          e.cancelBubble = true;
    }
}

UPDATE: Bear in mind that in your current code, if (e && e.stopPropagation) will always be true if the browser supports stopPropagation. If it goes into the second brace for cancelBubble, it will not remember the value last set. See this fiddle.

Basically, to summarise, in your code you're cancelling propagation every time after every click. You have to put some criteria into the function to determine whether or not to cancel the propagation up the element hierarchy.