Check the following code:
<div onclick="alert('Hi, from outer div!');">
<button onclick="alert('Hi, from button!');">Tha button</button>, Click me!
</div>
Is there a way to prevent the outer div from firing an onclick when I click the button? Any idea how to cancel DOM level 0 events?
Note: I can’t use jQuery. It needs to work on Chrome, FireFox, IE6-9.
Yes. In most standard browsers, you call
stopPropagationon the event object (live example | source):In older copies of IE, you have to set the
cancelBubbleproperty totrueinstead:…which means for broad compatibility you have to test which you’re dealing with, which gets ugly (live example | source):
These sorts of differences are why I always recommend moving away from the old DOM0-style handler and using a decent JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. These smooth over differences between browsers and provide a huge amount of utility functionality.
For example, with jQuery, this HTML:
…and this script (live example | source):
Or frequently with jQuery, you see people just doing
return false;in their event handler.return false;in a handler, in jQuery, does two things: Stops propagation, and prevents any default action the event might have had (for instance, in a click handler on a link).stopPropgationdoesn’t prevent the default.But this isn’t meant to be an advertisement for jQuery (though it is a very good library overall). Closure, YUI, Prototype, and all the others have similar functionality for letting you not worry about these sorts of browser incompatibilities.