Friday, April 15, 2011

Stop Parent event from firing

One funny problem you might face in this web world, you might add click event to parent and also add click event to child, but when you click on child element it also fires parent event :(

don't worry :) with just single line of Javascript code you can stop parent from being access to the child.

Here we go...

<div id="parent" onClick="imYourBoss()">
     <div id="child" onClick='imEmployee()'>
    </div>
</div>

in above example you can stop your parent by using following code :
<script>
$(function(){
$("#parent").click(function(){
     alert("Im your BOSS");
});

$("#child").click(function(event){
     event.stopPropagation();
     alert("Yeah I stop my boss from accessing me :)");
});
});
</script>

using stopPropagation technique we can prevent any parent handlers from being notified of the event.

stay tune for latest stuff :)