javascript tutorial - Event.preventDefault() Vs. return false - javascript - java script - javascript array



Problem:

When We want to prevent other event handlers from executing?

Solution 1:

return false from within a jQuery event handler is effectively the same as calling bothe.preventDefault and e.stopPropagation on the passed jQuery.Event object. e.preventDefault() will prevent the default event from occuring, e.stopPropagation() will prevent the event from bubbling up and return false will do both.

Solution 2:

From my experience, there is at least one clear advantage when using event.preventDefault() over using return false. Suppose we are capturing the click event on an anchor tag, otherwise which it would be a big problem if the user were to be navigated away from the current page. If your click handler uses return false to prevent browser navigation, it opens the possibility that the interpreter will not reach the return statement and the browser will proceed to execute the anchor tag's default behavior.

$('a').click(function (e) {
  // custom handling here

  // oops...runtime error...where oh where will the href take me?

  return false;
});
click below button to copy the code. By JavaScript tutorial team

The benefit to using 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).

$('a').click(function (e) {
  e.preventDefault();

  // custom handling here

  // oops...runtime error, but at least the user isn't navigated away.
});
click below button to copy the code. By JavaScript tutorial team

Solution 3:

When using jQuery, return false is doing 3 separate things when we call it:

  • event.preventDefault();
  • event.stopPropagation();
  • Stops callback execution and returns immediately when called.

Solution 4:

  • the best way to do is use preventDefault because if some exception raised in the handler then the return false statement will be skipped and the behavior will be opposite to what we want so it's better to use event.preventDefault() method
  • but if sure that the code wont trigger any exceptions then u can go with any of the method by your wish.
  • if u still want to go with the return false then we can put your entire handler code in try catch block like below
$('a').click(function (e) {
  try{
      your code here.........
  }
   catch(e){}
  return false;
});
click below button to copy the code. By JavaScript tutorial team

Solution 5:

My opinion from my experience saying, that it is always better to use

event.preventDefault() 
click below button to copy the code. By JavaScript tutorial team

Practically to stop or prevent submit event, whenever we required rather than return falseevent.preventDefault() works fine.


Related Searches to javascript tutorial - Event.preventDefault() Vs. return false