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;
}
}
For event capturing, we set the handler capture option to true: elem. addEventListener(event, handler, true) . By default, it is set to bubbling: false . In the example below, we add click event handlers on every HTML element using JavaScript for loop.
event.stopPropagation() This will stop any parent component's event from firing. To use this: Make sure to pass the event object as a parameter. Use the stopPropagation method on the event object above your code within your event handler function.
Definition and Usage. The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.
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.
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.
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