3228

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
    e.preventDefault();
});

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 about correct casing, parenthesis, etc.

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
RaYell
  • 69,610
  • 20
  • 126
  • 152
  • 181
    Note that jQuery's `preventDefault` does *not* prevent other handers from executing. That's what `stopImmediatePropagation` is for. – Crescent Fresh Aug 31 '09 at 12:22
  • 19
    @CrescentFresh, it does prevent other (subsequently bound) handlers from executing... on the DOM node the event is fired on. It just doesn't prevent propagation. – eyelidlessness Oct 17 '11 at 02:51
  • 42
    These are not "two methods of stopping event propagation?" e.preventDefault(); prevents the default action, it does not stop event propagation, which is done by e.stopPropagation(). – Timo Tijhof Jan 09 '12 at 01:44
  • 29
    This question and its answers are about jQuery. If you came here searching for a plain javascript answer, see [event.preventDefault() vs. return false (no jQuery)](http://stackoverflow.com/questions/18971284/event-preventdefault-vs-return-false-no-jquery) – Oriol Sep 28 '13 at 21:23
  • @Oriol jQuery is used in the question only to simplify the code examples. If you rewrite the jQuery selectors to plain-JS code you'll end up with the same problem and that's the reason that makes your question a duplicate. – RaYell Oct 08 '13 at 13:47
  • 6
    This answer has a table explaining it all http://stackoverflow.com/a/5302939/759452 – Adriano Apr 16 '14 at 07:20
  • 1
    you must consider differentation between vanilla js and jquery – javad bat Jun 12 '18 at 13:36
  • 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 occuring, e.stopPropagation() will prevent the event from bubbling up and return false will do both. Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up. – Ali NajafZadeh Aug 03 '21 at 16:59

14 Answers14

2970

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 occuring, e.stopPropagation() will prevent the event from bubbling up and return false will do both. Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.

Source: John Resig

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

Leo
  • 10,407
  • 3
  • 45
  • 62
karim79
  • 339,989
  • 67
  • 413
  • 406
  • 138
    `return false` from a DOM2 handler (`addEventListener`) does nothing at all (neither prevents the default nor stops bubbling; from a Microsoft DOM2-ish handler (`attachEvent`), it prevents the default but not bubbling; from a DOM0 handler (`onclick="return ..."`), it prevents the default (provided you include the `return` in the attribute) but not bubbling; from a jQuery event handler, it does both, because that's a jQuery thing. [Details and live tests here](http://blog.niftysnippets.org/2011/11/story-on-return-false.html) – T.J. Crowder Nov 30 '11 at 13:09
  • 13
    It would be helpful to define "Propagation" and "Default" here. I for one keep confusing them. Is this correct? **Propagation** = my code (JavaScript event handlers for parent elements). **Default** = browser code (links, text selection, etc.) – Bob Stein Jul 28 '13 at 14:49
  • 6
    what is really mean by bubbling? example? – Govinda Sakhare Aug 17 '16 at 10:59
  • 6
    +1 for noting that `return false` does _not_ stop event propagation in non-jQuery event handlers. i.e. `Test` does _not_ stop the event from bubbling up. – Doug S Aug 21 '16 at 02:42
  • 1
    @GovindaSakhare If you don't know what event bubbling means, you probably want to read and understand this whole page: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events – Mikko Rantalainen Sep 29 '22 at 15:26
453

From my experience, there is at least one clear advantage when using event.preventDefault() over using return false. Suppose you 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;
});

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 (eg. runtime error).

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

  // custom handling here

  // oops...runtime error, but at least the user isn't navigated away.
});
Jeff Poulton
  • 6,032
  • 1
  • 21
  • 12
  • 72
    Whilst true, the opposite behaviour is often preferable when doing progressive enhancement (which I think is probably the most likely reason to be overriding a default action) – meandmycode Apr 27 '12 at 22:53
  • Both are ways to block the default behaviour of an event, it's just a matter of what problem you're trying to solve. – Fabio Martins Feb 03 '20 at 21:00
112

This is not, as you've titled it, a "JavaScript" question; it is a question regarding the design of jQuery.

jQuery and the previously linked citation from John Resig (in karim79's message) seem to be the source misunderstanding of how event handlers in general work.

Fact: An event handler that returns false prevents the default action for that event. It does not stop the event propagation. Event handlers have always worked this way, since the old days of Netscape Navigator.

Event handler content attributes and event handler IDL attributes that returns false prevents the default action for that event handler.

What happens in jQuery is not the same as what happens with event handlers. DOM event listeners and MSIE "attached" events are a different matter altogether.

For further reading, see the[ [W3C DOM 2 Events documentation]][1].

Garrett
  • 2,936
  • 1
  • 20
  • 22
  • 6
    @rds That says "preventDefault doesn't stop further propagation of the event through the DOM. event.stopPropagation should be used for that." – Garrett Jul 24 '11 at 23:40
  • An [answer](http://stackoverflow.com/a/18971429/1709587) on a closely-related question alleges that prior to HTML 5, returning false from an event handler wasn't *specced* as doing anything at all. Now, maybe that's an incorrect interpretation of the (hard to understand) spec, or maybe despite it not being specced literally all the browsers interpreted `return false` the same as `event.preventDefault()`. But I dunno; it's enough to make me take this with a pinch of salt. – Mark Amery Jan 24 '16 at 00:13
  • 11
    I hate how every javascript search result in google is actually about jQuery, +1 – Alexander Derck Oct 11 '16 at 21:26
  • He has tagged it as both JavaScript and jQuery, and both are correct. `jQuery` is merely a sub-set of JavaScript, not its own language. – ProfK Jan 28 '20 at 05:26
  • @Garrett I'm just curious, could you explain me, why you decided to roll-back my edit before doing your own edit instead of simply adding another edit? My edit simply had updated your out-dated link and added the information about deprecation. It is fine that you decided to remove the link altogether now, but rolling back gave the impression as if my edit had been wrong, and it took me now again time to understand/guess that nothing had been wrong, but you just didn't like to refer to MDN anymore. – Sebastian Nov 06 '22 at 16:36
  • The MDN link is 404, so I removed it. https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Tutorial/More_Event_Handlers#Prevent_Default_Action and the MSDN link is wrong, too, as it linked to MDN, not MSDN: (See "For further reading, see attachEvent on MSDN") – Garrett Nov 08 '22 at 18:09
  • @Garrett I don't quite understand. As you can see in the edit history I had fixed your MDN link to this one, which is working - no 404: https://developer.mozilla.org/en-US/docs/Web/API/Event/returnValue That's exactly why I asked why you had rolled back my edit. The other link wasn't touched by me. – Sebastian Nov 12 '22 at 21:00
  • @Sebastian The MDN link you provided is to `event.returnValue`, an event property of the Internet Explorer's event model (window.event). Returning false from an event handler Event.returnValue is not `return false`. – Garrett Nov 14 '22 at 16:11
  • 1
    MSDN is now rewriting history to pretend that its history is now that of current Firefox. Rewriting history is nothing new for governments, and is a tool of power, for perception management. How casually and laughably MSDN rewrites history with event.returnValue. That's not reality, however. https://lists.w3.org/Archives/Public/www-style/2010Sep/0458.html — – Garrett Nov 14 '22 at 16:14
  • @Garrett Oh, thanks, I finally got it! In spite of prominently being `Event.returnValue` written on the page title, I read it as the return value of the event handler. Thanks for clarifying. Nevertheless these two used to be related ... ; ) – Sebastian Nov 14 '22 at 17:13
72

Generally, your first option (preventDefault()) is the one to take, but you have to know what context you're in and what your goals are.

Fuel Your Coding has a great article on return false; vs event.preventDefault() vs event.stopPropagation() vs event.stopImmediatePropagation().

JosefAssad
  • 4,018
  • 28
  • 37
JAAulde
  • 19,250
  • 5
  • 52
  • 63
60

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.

Samuel Katz
  • 24,066
  • 8
  • 71
  • 57
James Drinkard
  • 15,342
  • 16
  • 114
  • 137
47

You can hang a lot of functions on the onClick event for one element. How can you be sure the false one will be the last one to fire? preventDefault on the other hand will definitely prevent only the default behavior of the element.

user66001
  • 774
  • 1
  • 13
  • 36
Eldar Djafarov
  • 23,327
  • 2
  • 33
  • 27
  • You do not need to let the last event handler return false. Any handler can return false to prevent the default behavior. See https://myprogrammingnotes.com/preventdefault-cancelbubble-true-return-false-and-returnvalue-false.html – peter May 19 '22 at 09:06
23

I think

event.preventDefault()

is the w3c specified way of canceling events.

You can read this in the W3C spec on Event cancelation.

Also you can't use return false in every situation. When giving a javascript function in the href attribute and if you return false then the user will be redirected to a page with false string written.

user66001
  • 774
  • 1
  • 13
  • 36
rahul
  • 184,426
  • 49
  • 232
  • 263
19

I think the best way to do this is to use event.preventDefault() because if some exception is raised in the handler, then the return false statement will be skipped and the behavior will be opposite to what you want.

But if you are sure that the code won't trigger any exceptions, then you can go with any of the method you wish.

If you still want to go with the return false, then you can put your entire handler code in a try catch block like below:

$('a').click(function (e) {
  try{
      your code here.........
  }
   catch(e){}
  return false;
});
Daniel
  • 11,332
  • 9
  • 44
  • 72
Naga Srinu Kapusetti
  • 1,563
  • 15
  • 12
4

The main difference between return false and event.preventDefault() is that your code below return false will not be executed and in event.preventDefault() case your code will execute after this statement.

When you write return false it do the following things for you behind the scenes.

* Stops callback execution and returns immediately when called.
* event.stopPropagation();
* event.preventDefault();
Abdullah Shoaib
  • 416
  • 1
  • 5
  • 18
1

e.preventDefault();

It simply stops the default action of an element.

Instance Ex.:-

prevents the hyperlink from following the URL, prevents the submit button to submit the form. When you have many event handlers and you just want to prevent default event from occuring, & occuring from many times, for that we need to use in the top of the function().

Reason:-

The reason to use e.preventDefault(); is that in our code so something goes wrong in the code, then it will allow to execute the link or form to get submitted or allow to execute or allow whatever action you need to do. & link or submit button will get submitted & still allow further propagation of the event.

<!DOCTYPE html>
<html lang="en" dir="ltr">
   <head>
      <meta charset="utf-8">
      <title></title>
   </head>
   <body>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <a href="https://www.google.com" onclick="doSomethingElse()">Preventsss page from redirect</a>
      <script type="text/javascript">
         function doSomethingElse(){
           console.log("This is Test...");
         }
         $("a").click(function(e){
          e.preventDefault(); 
         });
      </script>
   </body>
</html>

return False;

It simply stops the execution of the function().

"return false;" will end the whole execution of process.

Reason:-

The reason to use return false; is that you don't want to execute the function any more in strictly mode.

<!DOCTYPE html>
<html lang="en" dir="ltr">
   <head>
      <meta charset="utf-8">
      <title></title>
   </head>
   <body>
      <a href="#" onclick="returnFalse();">Blah</a>
      <script type="text/javascript">
         function returnFalse(){
         console.log("returns false without location redirection....")
             return false;
             location.href = "http://www.google.com/";
         
         }
      </script>
   </body>
</html>
Parth Raval
  • 4,097
  • 3
  • 23
  • 36
1

Basically, this way you combine things because jQuery is a framework which mostly focuses on HTML elements, you basically preventing the default, but at the same time, you stop propagation to bubble up.

So we can simply say, return false in jQuery is equal to:

return false is e.preventDefault AND e.stopPropagation

But also don't forget it's all in jQuery or DOM related functions, when you run it on the element, basically, it prevents everything from firing including the default behaviour and propagation of the event.

Basically before starting using return false;, first understand what e.preventDefault(); and e.stopPropagation(); do, then if you think you need both at the same time, then simply use it.

So basically this code below:

$('div').click(function () {
  return false;
});

is equal to this code:

$('div').click(function (event) {
  event.preventDefault();
  event.stopPropagation();
});
Alireza
  • 100,211
  • 27
  • 269
  • 172
1

From my experience event.stopPropagation() is mostly used in CSS effect or animation works, for instance when you have hover effect for both card and button element, when you hover on the button both card and buttons hover effect will be triggered in this case, you can use event.stopPropagation() stop bubbling actions, and event.preventDefault() is for prevent default behaviour of browser actions. For instance, you have form but you only defined click event for the submit action, if the user submits the form by pressing enter, the browser triggered by keypress event, not your click event here you should use event.preventDefault() to avoid inappropriate behavior. I don't know what the hell is return false; sorry.For more clarification visit this link and play around with line #33 https://www.codecademy.com/courses/introduction-to-javascript/lessons/requests-i/exercises/xhr-get-request-iv

0

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

event.preventDefault() 

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

ann
  • 576
  • 1
  • 10
  • 19
Dilip Langhanoja
  • 4,455
  • 4
  • 28
  • 37
  • 14
    Better why? You've literally given zero justification whatsoever here. -1. – Mark Amery Jan 23 '16 at 23:07
  • In the case there are multiple event bindings, e.preventDefault() is more targeted than return false. – Taiger Aug 22 '17 at 22:50
  • `preventDefault` is some english words I understand it "prevents the default". `return false` is some english words I understand it "returns false" but I have no idea why until I Google this cryptic code. And bonus, I can control separatly `stopPropagation` and `preventDefault `. – Joan Mar 28 '18 at 17:25
0

preventDefault() and return false are different ways to prevent the default event from happening.

For example, when a user clicks on an external link, we should display a confirmation modal that asks the user for redirecting to the external website or not:

hyperlink.addEventListener('click', function (e) {
    // Don't redirect the user to the link
    e.preventDefault();
});

Or we don't want to submit the form when clicking its submit button. Instead, we want to validate the form first:

submitButton.addEventListener('click', function (e) {
    // Don't submit the form when clicking a submit
    e.preventDefault();
});

Differences

  1. return false doesn't have any effect on the default behavior if you use the addEventListener method to handle an event. It only works when the event handler is declared as an element's attribute:
hyperlink.addEventListener('click', function (e) {
     // Does NOT work
     return false;
 });
    
 // Work
 hyperlink.onclick = function (e) {
     return false;
};
  1. According to the HTML 5 specifications, return false will cancel the event except for the mouseover event.

Good practices

  1. It's recommended to use the preventDefault method instead of return false inside an event handler. Because the latter only works with using the onclick attribute which will remove other handlers for the same event.

  2. If you're using jQuery to manage the events, then you're able to use return false within the event handler:

$(element).on('click', function (e) {
        return false;
});

Before returning the value of false, the handler would do something else. The problem is that if there's any runtime error occurring in the handler, we will not reach the return false statement at the end.

In that case, the default behavior will be taken:

$(element).on('click', function (e) {
    // Do something here, but if there's an error at runtime
    // ...
    return false;
});

We can avoid this situation by using the preventDefault method before performing any custom handler:

$(element).on('click', function (e) {
    e.preventDefault();

    // Do something here
    // The default behavior is prevented regardless of errors at runtime
    // ...
});

Good to know

If you're using jQuery to manage the event, then return false will behave the same as the preventDefault() and stopPropagation() methods:

$(element).on('click', function (e) {
    // Prevent the default event from happening and
    // prevent the event from bubbling up to the parent element
    return false;
});
samnoon
  • 1,340
  • 2
  • 13
  • 23