970_90

Tuesday, 24 March 2015

What is difference between event.preventDefault() and return false in Javascript?

What is difference between event.preventDefault() and  return false in Javascript?


e.preventDefault() will prevent the default event from occuring.
Means If this method is called, the default action of the event will not be triggered.

This method does not accept any arguments.
Example:
jQuery(document).ready(function(){
    $('a.link').click(function (e) {
        e.preventDefault();
    });
});



e.stopPropagation() will prevent the event from bubbling.
Means If this method is called, It Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

This method also does not accept any arguments.
Example:
jQuery(document).ready(function(){
    $('a.link').click(function (e) {
        e.stopPropagation();
    });
});



return false: Will do above both that is preventDefault & stopPropagation.
Example:
jQuery(document).ready(function(){
    $('a.link').click(function (e) {
        return false;
    });
});




No comments:

Post a Comment