Sunday, March 22, 2009

EventBubble in Javascript

Today I came across a cool method of Javascript. Basically I was trying to fix a long running bug. The underlying issues was something similar:

<tr id="idTR" class="some-Tr-Class" onclick="javascript:Ajsclass.doTRWork();" >

<td class="some-Td-Class" onclick="_do_nothing()">

<input type="checkbox" id="dynamicallyGen" value="xyz">

<td class="some-Td-Class">

..Some title..

</td>

.....
....

</tr>



My Issue is I want to override the Ajsclass.doTRWork();. for the first TD with the checkbox. Was wondering how to
to fix it. Finally Mozilla helped me with their API documentation.

The solution is to not call the bubble function which is Ajsclass.doTRWork(); Just stop after _do_nothing().

The solution is to add:

event.cancelBubble = true;


in the _do_nothing().

The above works fine for Firefox but not for IE


For IE add the following:

event.stopPropagation()


Cool aha? I started liking javascript right from the beginning of this project as 70% of my work was Ajax & JS.