Saturday, May 2, 2009

How to prevent current event's propagation

Think about next scenario:

Create a table.
Each row shows information on click.
Each column shows information on click.
Each column can contain additional clickable tags.

The implementation:

<table>

<tr onclick="alert('row');">

<td onclick="alert('td');">

<span onclick="alert('td');" style="color:blue;" >

Click here!

</span>

&nbsp; td section

</td>

</tr>

</table>

That is because when method is called by any EventListener the event will cease propagating through the tree.

To prevent the propagation after “Click here!” text click use following code:

<table>

<tr onclick="alert('row');">

<td onclick="alert('td');">

<span onclick="spanClick(event);" style="color:blue;" >

Click here!

</span>

&nbsp; td section

</td>

</tr>

</table>


<script>

function spanClick(e)

{

alert('span');

if(!e) var e = window.event;

try{e.cancelBubble = true; return;}catch(e){} // IE

try{e.stopPropagation(); return;}catch(e){} // FireFox

}




0 comments:

Post a Comment