Wednesday, October 31, 2012

Javascript Event Bubbling


I have a Div element with a small Span element inside it, on my webpage. I have attached two alerts against the click event of each elements. The code snippet and screen-shot is given below.

HTML
-------
<div onclick="javascript:alert('Outer DIV Clicked')">
     <span onclick="javascript:alert('Inner Span Clicked')">?</span>
</div>

Problem :: 
When we click on anywhere within the Div element, the message "Outer DIV Clicked" is shown, but when we click on the inner question mark icon [inside the Span element], "click" events of both the elements [Span and Div] are sequentially fired and as a result the following messages are shown on screen one by one.

Inner Span Clicked
Outer DIV Clicked















At first, the click event of Span is fired, then same event of outer Div is fired. This type of incident is called event bubbling. We can stop this kind of behaviour in the following way.

Solution :: 
We need to re-write the Span element as the following way

<span onclick="span_click(event)">?</span>

and we need to write the "span_click" function as shown below.

<script>
function span_click(e)
{
  if (!e) var e = window.event;
  e.cancelBubble = true;   // for IE
  if (e.stopPropagation) 
    e.stopPropagation();   // for Firefox 
  alert('Inner Span Clicked');
}
</script>

By manipulating the "cancelBubble" property available with IE browser and calling stopPropagation() method in Firefox browser, we can stop this event bubbling. Just check this out.

Find more on Event Bubbling in next article "Javascript Event Bubbling 2"

No comments: