[javascript] event.preventDefault() vs. return false

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?

The answer is


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;
});

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();

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.

The documentation from MDN explains how return false in an event handler works

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 attachEvent on MSDN and the W3C DOM 2 Events documentation.


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

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.


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

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.

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

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.

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


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.


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.


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.


Prevent Default

Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur. You can use Event.

return false

return false inside a callback prevents the default behaviour. For example, in a submit event, it doesn't submit the form. return false also stops bubbling, so the parents of the element won't know the event occurred. return false is equivalent to event.preventDefault() + event.stopPropagation()


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().


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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to event-handling

How to call function on child component on parent events How to use onClick with divs in React.js Touch move getting stuck Ignored attempt to cancel a touchmove Calling one method from another within same class in Python How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer? How to use the DropDownList's SelectedIndexChanged event Android Overriding onBackPressed() How to pass event as argument to an inline event handler in JavaScript? Get clicked element using jQuery on event? How can I show a hidden div when a select option is selected?

Examples related to dom-events

Detecting real time window size changes in Angular 4 Does Enter key trigger a click event? What are passive event listeners? Stop mouse event propagation React onClick function fires on render How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over iFrame onload JavaScript event addEventListener, "change" and option selection Automatically pass $event with ng-click? JavaScript click event listener on class

Examples related to event-propagation

React prevent event bubbling in nested components on click Stop mouse event propagation Prevent scrolling of parent element when inner element scroll position reaches top/bottom? How do I prevent a parent's onclick event from firing when a child anchor is clicked? event.preventDefault() vs. return false