Yes. In most standard browsers, you call stopPropagation
on the event object (live example | source):
<div onclick="alert('Hi, from outer div!');">
<button onclick="alert('Hi, from button!'); event.stopPropagation();">Tha button</button>, Click me!
</div>
In older copies of IE, you have to set the cancelBubble
property to true
instead:
<div onclick="alert('Hi, from outer div!');">
<button onclick="alert('Hi, from button!'); event.cancelBubble = false;">Tha button</button>, Click me!
</div>
...which means for broad compatibility you have to test which you're dealing with, which gets ugly (live example | source):
<div onclick="alert('Hi, from outer div!');">
<button onclick="alert('Hi, from button!'); if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; }">Tha button</button>, Click me!
</div>
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:
<div id="theDiv">
<button id="theButton">Tha button</button>, Click me!
</div>
...and this script (live example | source):
$("#theDiv").click(function() {
alert('Hi, from outer div!');
});
$("#theButton").click(function(event) {
alert('Hi, from button!');
event.stopPropagation(); // Even on IE, jQuery provides this
});
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). stopPropgation
doesn'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.