Event Propagation
Event Propagation Stops the Event from bubbling or making the event Chain .
Example : - A Click Event on a <td> tag will also fire click event on it's parent <tr> and this event chain also continues to parent <table> tag of that <tr> this makes a event chain in order to stop this event Chain propagation we can Use StopPropagation that Prevents this from happening.
StopPropagation ( ) will stop that event from happening on parent (the entire ancestors). When We Use StopPropagation only < td > Event will fire as per our Example above its parent < tr > or < table > Click event will not fire .
StopPropagation ( ) Tells downward propagation of the event is stopped and also its upward propagation
CODE EXAMPLE
<div onclick='executeParent()'>
<a href='http://google.com'>Click here to visit google.com</a>
</div>
<script>
$('a').click(function(event) {
event.stopPropagation();
$('a').text('Click event is going to be executed');
$('a').contents().unwrap();
});
function executeParent() {
alert('here');
}
</script>
CODE EXPLANATION
If you execute the code above, the function executeParent() will not be called and you will not get the javascript alert this time. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit google.com‘ replaced by the text ‘Click event is going to be executed‘ and immediately you will be redirected to google.com. This is because we haven’t prevented the default click action from triggering this time using event.preventDefault() method.
0 Comment to "Javascript Event StopPropagation"
Post a Comment