Hi,
I read about the tunneling and bubbling of events in javascript. After reading the history about the events and how that helps to do handle events at various levels; I thought of sharing my insight on that.
There are already enough materials which can be found on internet regarding this. I thought of presenting simplest model to present the difference between
e.preventDefault and
e.stopPropogation.
The core concept about the events order is explained in a very nicely written blog post I found. Instead of rewriting the same in different form, I thought of sharing the link of the same. Here is it -->
Events Order.
Now being acquinted with the history, now I can explain the usage and difference of mentioned events in the title.
e.preventDefault: This event is used to cancel the default behavior of the element it is bound to.
e.stopPropogation: This event prevents the event from bubbling further in DOM.
HTML
<div>
<a type="button" href="navigate.com">Click Me!</a>
</div>
Javascript
jQuery("a").parent.onclick(function(e){
alert('from parent');
});
//code 1
jQuery("a").onclick(function(e){
e.preventDefault();
alert('Preventing Default calling');
});
//code 2
jQuery("input").onclick(function(e){
e.stopPropogation();
alert('Preventing Propagation of Event');
});
In
code 1 e.preventDefault() is called is suppress the
href and cancels the navigation of the page. But in this the event written for parent is also called.
In
code 2 e.stopPropogation() stops the bubbling of the event but
href navigation happens. So here the event written for parent is not called.
After learning about these event a question pop-up in mind isn't the functionality provided by
e.preventDefault() is similar to that of
return false statement written in the end.
Well the functionality provided in similar but there is a noticeable difference.
Lets modify
code 1 to see the difference
//code 1.1
jQuery("a").onclick(function(e){
e.preventDefault();
err(); // error code
alert('Preventing Default calling');
});
//code 3
jQuery("a").onclick(function(e){
err(); // error code
alert('Preventing Default calling');
return false;
});
Consider the
err() function as some error has occurred in the code. Since we are not handling the exception the code is going to break. But in case of
code1 calling
e.preventDefault() prevent's the default behavior of the element, so the page still won't navigate to a new link.
But in
code 3 , it doesn't reaches the statement
return false. So the default behavior is called and the page navigates.
I hope this helped you. If you have any queries, do comment.