Javascript prevent event bubbling parent child when fired


Javascript can be a braincracker at some times. As it happened to be so for me trying to make bubbling stop towards a parent element when firing an event from a child element.

For starters ,bubbling means that the event is given to the target, and then its parent, and then its parent, and so on until the event is canceled.

For instance the following example, when we click the child div(FunctionB), bubbling would start firing all onClick events(like FunctionA) from elements we call parent, ancestor etc.

bubbling

It's important to note that in this case the child onClick event will always be fired first, thus making a true bubble effect.

We can use the following function to add an eventListener to our child object :
if(childDiv && childDiv.addEventListener){

childDiv.addEventListener('click',function(event){event.cancelBubble=true;if(event.stopPropagation) event.stopPropagation();},false);

}else if(childDiv && childDiv.attachEvent){

childDiv.attachEvent('onclick',function(event){event.cancelBubble=true;if(event.stopPropagation) event.stopPropagation();});

}else{ 

childDiv.onclick=function(event){event.cancelBubble=true;if(event.stopPropagation) event.stopPropagation();}

}
First the script checks if addEventListener (Firefox) is supported. Then it will check if attachEvent (Internet Explorer) is supported.
Otherwise just use the regular method, might want to try{ }catch(e){} it to prevent any errors in unsupported browsers.

Each time we check for the existence of the function stopPropagation. Only then we use it. As it doesn't work in IE, because it's created by Mozilla.
if(event.stopPropagation) event.stopPropagation();


Why did this take a while to create you ask? Well, consider building this function from scratch. Internet Explorer isnt very helpful with error reporting, it can take hours to find out what function works where.



Posted by James on 2009-07-15 in the category " javascript "