Javascript Tip: Event Propagation



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 isnt 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.







Comments



Works in Firefox

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


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

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.


Post comment

Name *
Email
Title
Body *
Security Code
*
* Required fields

Related Posts

Latest Posts

Be the best stalker you can be


2011-12-13 22:33:54

Syntactic sugar (C#): Enum


2011-08-04 16:50:18

Top 5 posts

Simple WYSIWYG Editor


Creating a WYSIWYG textbox for your website is actually quite simple.
2007-02-01 12:00:00

Moving items between listboxes in ASP.net/PHP example


Move items between two listboxes in ASP.net(C#, VB.NET) and PHP
2008-06-12 17:07:43

Cross Browser Issues: Firefox Word Wrapping


Firefox word wrapping issues
2008-06-09 09:51:21

Populate a TreeView Control C#


Populate a TreeView control in a windows application.
2009-08-27 16:01:03

C# YouTube : Google API


Post on how to integrate with YouTube using the Google Data API
2011-03-12 08:37:51