event.preventDefault() vs. return false

Solution:

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

e.preventDefault()  will stop the default event from happening,  e.stopPropagation() prevents the event from bubbling over, and  return false  does both. This behavior is different from non-jQuery event handlers.  return false , for example, does not prevent the event from bubbling.

Source: John Resign

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

From my experience, there is at least one clear advantage when using event.preventDefault() over using return false. Imagine that you are recording the click event from an anchor tag. Otherwise, it could be a problem if the user navigates away from the current page. To prevent browser navigation, a click handler may use return false. The interpreter might not reach the return statement and the browser will continue to perform 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;
});

The benefit to using event.preventDefault() is that you 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 (e.g., runtime error).

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

  // custom handling here

  // oops...runtime error, but at least the user isn't navigated away.
});

This is not a “JavaScript question” as you have titled it. It is a question about the design of jQuery.

jQuery and John Resigns previously linked citation (in karim79’s message) seem like the main source of confusion about how event handlers work in general.

Fail: Event handlers that return false information prevent the default action from being taken for an event. This does not stop event propagation. Since the early days of Netscape Navigator, event handlers have been doing this since.

MDN’s documentation explains how an event handler return false .

The events that happen in jQuery are not the same as those that occur with event handlers. MSIE “attached” events and DOM event listeners are two different things.

Further reading is available at attach-event MSDN or the W3CDOM 2 Events documentation.

Exit mobile version