event.preventDefault() vs. return false

Asked : Nov 17

Viewed : 72 times

When I want to prevent other event handlers from executing after a certain event is fired, I can use one of two techniques. I'll use jQuery in the examples, but this applies to plain-JS as well:

1. event.preventDefault()

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

2. return false

$('a').click(function () {
    // custom handling here
    return false;

Is there any significant difference between those two methods of stopping event propagation?

For me, return false; is simpler, shorter, and probably less error-prone than executing a method. With the method, you have to remember the correct casing, parenthesis, etc.

Also, I have to define the first parameter in a callback to be able to call the method. Perhaps, there are some reasons why I should avoid doing it like this and use preventDefault it instead? What's the better way?

javascript jquery event-handling dom-events event-propagation 
3 Answers

return false from within a jQuery event handler is effectively the same as calling both e.preventDefault and e.stopPropagation on the passed jQuery.Event object.

e.preventDefault() will prevent the default event from occurring, e.stopPropagation() will prevent the event from bubbling up, and return false will do both. Note that this behavior differs from normal (non-jQuery) event handlers, which, notably, return false does not stop the event from bubbling up.

Any benefit to using event.preventDefault() over "return false" to cancel out an href click?

answered Jan 17

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

  1. event.preventDefault();
  2. event.stopPropagation();
  3. Stops callback execution and returns immediately when called.

See jQuery Events: Stop (Mis)Using Return False for more information and examples.

answered Jan 17

The preventDefault stops the default browser behavior when an event is fired like not redirecting the page on URL click etc.

The return false also stops the default browser behavior when an event is fired and does not let the event propagate. The callback execution is also stopped is returned immediately when called.

answered Jan 17

Login and Submit Your Answer
Browse other questions tagged  javascript  jquery  event-handling  dom-events  event-propagation or ask your own question.