Javascript Tip: Event Propagation

July 25, 2010 by JavaScript  

Observe the following markup:

<script type="text/javascript">

	function message(text)
	{
		alert(text);
	}
	
</script>

<div style="width:100px">
	<div style="background-color:red; padding:10px;" onclick="message('a')">
		<div style="background-color:green; padding:10px;" onclick="message('b')">
			<div style="background-color:blue; padding:10px;" onclick="message('c')">
			</div>
		</div>
	</div>
</div>

What we've got here is various nested div tags with attached events.

You will find that if you click on the blue block (for example), three alert boxes will be displayed - alerting c, b and a.

What happens is that the events attached to the parent nodes propagates to its child nodes - which means that triggering events from a child node will also trigger the attached events in its various parent nodes.

Now this isn't always the desired effect - luckily its possible to stop propagation of events like so:

function StopPropagation(e)
{
	if (window.event) {
		e.cancelBubble=true; // IE
	} else {
		e.stopPropagation(); // Others
	}
}

We alter our event handler like this:

function message(text, e)
{
	alert(text);
	StopPropagation(e);
}

Within our markup (where we attach the event in this case), we simply need to pass the current event to our method.

<div style="width:100px">
	<div style="background-color:red; padding:10px;" onclick="message('a', event)">
		<div style="background-color:green; padding:10px;" onclick="message('b', event)">
			<div style="background-color:blue; padding:10px;" onclick="message('c', event)">
			</div>
		</div>
	</div>
</div>

If we click on the blue block now, you will notice that only c gets alerted - since we stopped propagation of events.


Leave a Comment


Works in Firefox December 1, 2010 by Christoff Truter

Works 100% in firefox, what issues are you experiencing?

November 18, 2010 by jeffsnox

Solved my problem. It is essential in Firefox et al that the "event" parameter is the first in the list if there's more than one.

This doesn't work November 18, 2010 by jeffsnox

This does not work in Firefox. It throws a wobbler on the use of the 'event' word in the function call. In IE it should be "window.event" I believe.