Fast Tip: Breaking events propagation in Javascript
Friday, December 19th, 2008An important feature of Javascript you must know is the events propagation. This what makes is trigger all events to the parents when a child event is captured (like a bubble). So, if you click in a div element, the click will active the onclick event in the div parent, and in the grandparent… and so until the body element.
This can often be helpful, but many others can be a big trouble. Of course you can disable this feature with the code below:
[code language="Javascript"] /*DISABLE EVENTS PROPAGATION*/ //IE if(!e) window.event.cancelBubble = true; //OTHER NAVIGATORS* else if(e.stopPropagation) e.stopPropagation(); [/code]
You can view a little example so that you can see it in action after the break.
Tested in: Firefox, Internet Explorer 6 & 7, Opera, Safari & Chrome.