JavaScript - Prevent Event Bubbling... ?

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

JavaScript - Prevent Event Bubbling... ?

Post 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?
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post 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!
Last edited by Kieran Huggins on Mon Jan 08, 2007 9:39 am, edited 2 times in total.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

w00t!

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