Page 1 of 1

JavaScript - Prevent Event Bubbling... ?

Posted: Mon Jan 08, 2007 9:21 am
by Chris Corbyn

Code: Select all

<div onclick="alert('Outer div clicked');">
    <div onclick="alert('Inner div clicked');">
    </div>
</div>
When you click on an element which has an event attached to it, the event fires obviously. If the parent element has the same event attached to it then that fires too. So in the above example two alerts will fire - first the inner one, followed by the outer one. That's normal and it's called "event bubbling".

Question: How do I stop the event bubbling in browsers other than IE? I've seen it done with IE some time in the past but I know that code was IE-specific. Anybody know how to burst the bubble and just have the inner alert be shown?

Posted: Mon Jan 08, 2007 9:33 am
by Kieran Huggins
from ppk: http://www.quirksmode.org/js/events_order.html

Code: Select all

window.event.cancelBubble = true; // ie

e.stopPropagation(); // moz

function doSomething(e) // cross browser
{
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}
Edited to change the code syntax to javascript :banghead I need more caffeine!

Posted: Mon Jan 08, 2007 9:38 am
by Chris Corbyn
w00t!

Thank you. I did search I swear... I just kept getting pages that only talked about ie :(