jQuery-return false vs prevent default method

Wikitechy | 357 Views | jquery | 03 Jun 2016

 

Example 1:

$('a').click(function (e) {
// custom handling here
// oops...runtime error... where will the href take me?

return false;
});
  • Over here we have an benefit, When using the method event.preventDefault() over the statement return false , then the capturing of click event on an anchor tag occurs.
  • When we use the method event.preventDefault()  , then the event will navigate away from the current page.
  • If we click the event handler, it returns false in order to prevent from the browser navigation.
  • And apart from this, if we cannot the interpret the event handler then it will not reach the return statement, instead the browser will proceed to execute the default behavior of the anchor tag's.

Example 2:

$('a').click(function (e) {
e.preventDefault();
// custom handling here
// oops...runtime error, but at least the user isn't navigated away.

});
  • The benefit of using the event event.preventDefault() is that we can add this as the first line in the handler, thereby guaranteeing that the anchor's default behavior will not fire, regardless if the last line of the function is not reached (eg. runtime error).

Return false is doing 3 separate things when we call it:

1.event.preventDefault();

2.event.stopPropagation();

3.Stops callback execution and returns immediately when called.




Workshop

IOT Hackathon
Webinar

Join our Community

Advertise