When a user clicks or performs another event on an HTML element it propigates up the chain.
For example in the following code , when a user clicks on the blue box it triggers an event in both the blue and yellow boxes.
<div style="WIDTH: 200px; HEIGHT: 200px; BACKGROUND-COLOR: yellow" onclick="alert('2 clicked');">l 2 <div style="WIDTH: 100px; HEIGHT: 100px; BACKGROUND-COLOR: cyan" onclick="alert('1 clicked');">1</div</div>
Click on blue to see.
Clicking on yellow doesnt trigger a blue event because the events move up and not down the chain.
2
1
This behaviour can be useful because when the mouse is clicked in blue Yellow knows about it, so blue can ignore the event and let it be handled by yellow.
Sometimes you want to stop events being passed on to parent elements. The following code shows how to do this.
In the following code e represents the event object.
if (e.stopPropagation) e.stopPropagation(); //Code used for w3c compatible browsers (eg firefox)
else
e.cancelBubble = true; // code used for Internet Explorer
Incorporating this code into our example.
function test(e,message){
if(!e) e=window.event;
if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true;
alert(message);
}
<div style="WIDTH: 200px; HEIGHT: 200px; BACKGROUND-COLOR: yellow" onclick="test(event,'2 clicked');">l 2 <div style="WIDTH: 100px; HEIGHT: 100px; BACKGROUND-COLOR: cyan" onclick="test(event,'1 clicked');">1</div</div>
I cant demonstrate this script as blogspot isnt recognising my script tags.

No comments:
Post a Comment