Wednesday, May 20, 2009

Stop JavaScript event bubbling

JavaScript performs event bubbling in the sense that when an event like omouseover, onclick, etc occurs in the child controls it is raised for the containing controls also till the outermost parent containing control. Suppose we have a HTML structure like this

   1:  <div id="blockDiv"> 


   2:       <span><a href="http://www.example.com/">The quick brown fox jumps over the lazy dog. 


   3:              </a>


   4:       </span> 


   5:        <p> 


   6:              Nothing much


   7:        </p> 


   8:   </div>




 



where Div is the parent control containing span which further contains a (link). Now when onmouseout occurs on a (link) after we take our mouse pointer out of it, 2 more events fire at the same time. onmouseout of span as well as onmouseout of div. This is the called event bubbling and the default behaviour of JS. If you have some script written on these 2 mouseouts, it will unnecessarily fire.



 



How to stop this: Its quite easy to via the stopPropagation() method in JS



function aout (event){

//Do something on a link mouseout

event.stopPropagation();

}



 







No comments: