We have many times have listen about event bubbling in javascript which propogate an event from child element to parent element.
So, to avoid such event bubbling in our page we use event.stopPropogation or return false. Also there is a new thing called event.preventDefault which is used to prevent any defalt funtionality of the element.
event.preventDefault() is used to stops the default browsers behaviour.
event.stopPropagation() is used to prevents the event from propagating the DOM.
return false does these two thing and also Stops callback execution and returns immediately when called.
Example of event.preventDefault():
HTML:
<div onclick='prevent()'>
<a href='http://findnerd.com'>Click here to visit findnerd.com</a>
</div>
JS:
$('a').click(function(event) {
event.preventDefault();
$('a').text('Preventing click event');
});
function prevent() {
console.log('I m here..');
}
After excuting this code first thing that come is the console of "I m here.." then your content from "Click will here to visit findnerd.com" will change to "Preventing click event" and will redirect to findnerd.com. This is due to event.preventDefault() method we used to prevent the default click action to be triggered.
Example of event.stopPropagation():
HTML:
<div onclick='propogation()'>
<a href='http://findnerd.com'>Click here to visit findnerd.com</a>
</div>
JS:
$('a').click(function(event) {
event.stopPropagation();
$('a').text('Now executing click event..');
});
function propogation() {
console.log('I m here..');
}
After excuting this code it will not execute the propogation()function and then your content from "Click will here to visit findnerd.com" will change to "Preventing click event" and will redirect to findnerd.com. This is because we haven’t prevented the default click action from triggering this time using event.preventDefault() method.
Example of return false:
HTML:
<div onclick='returning()'>
<a href='http://findnerd.com'>Click here to visit findnerd.com</a>
</div>
JS:
$('a').click(function(event) {
$('a').text('Preventing click event');
return false;
});
function returning() {
alert('here');
}
If you execute the code above, you will get the exact same results. This due to return false statement doing the job of both event.preventDefault() and event.stopPropagation() methods.
0 Comment(s)