Wednesday, October 31, 2012

Javascript Event Bubbling 2

I have already discussed the issues related to Event Bubbling behaviour in various browsers in article "Javascript Event Bubbling". I just have another small example of such event bubbles shown below.


HTML
-------  

<div>
   <a href="javascript:alert('ANCHOR clicked')">
     <span style='font-weight:bold' onclick="alert('SPAN clicked');">SPAN</span> Anchor
   </a>
</div>

The output of above HTML is shown below.















The text "Anchor" is appearing inside the Anchor tag . When it is clicked , "ANCHOR clicked" message is shown. But when an child element of this anchor, a span element with text "SPAN" is clicked, the message "SPAN clicked" message is shown as span element's click event is fired. Next, span element's parent is an Anchor tag which has "click" event defined also. Due to Event Bubbling effect, "click" event of the Anchor tag is also fired and as a result, both the messages "SPAN clicked" and "ANCHOR clicked" are alerted on screen one by one. If the anchor tag had a parent element with its own click event, that would have also been fired in the same process. 

To prevent this, we can make a small change in the above HTML as shown below.

<div>
   <a href="javascript:alert('ANCHOR clicked')">
     <span style='font-weight:bold' onclick="alert('SPAN clicked'); return false;">SPAN</span> Anchor
   </a>
</div>

We have appended a "return false;" statement to the "onclick" property of the Span element. And by doing this, the control does not pass form child's triggered event to parent's similar event. The above solution ran perfectly on Chrome, Firefox and IE 6,7,8,9.

No comments: