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.
Posted by - Christoff Truter
Date - 2010-07-25 21:59:29
Comments
Post comment