[Javascript] event.preventDefault() vs. return false (no jQuery)


Answers

Difference between preventDefault, stopPropogation, return false

Default Action – Server side action when control event raise.

Suppose we have div control and inside it we have a button. So div is the parent control of the button. We have Client side click and server side click event of the button. Also we have client side click event of the div.

On click event of the button on client side, we can control the actions of parent control and server side code using following three ways:

  • return false - This allow only client side event of the control. Server side event and client side event of the parent control is not fired.

  • preventDefault() - This allow client side event of control and its parent control. Server side event ie. Default action of the control is not fired.

  • stopPropogation() – This allow client side as well as server side event of the control. Client side event of the control is notallowed.

Question

I wondered if event.preventDefault() and return false were the same.

I have done some tests, and it seems that

  • If the event handler is added using old model, for example

    elem.onclick = function(){
        return false;
    };

    Then, return false prevents default action, like event.preventDefault().

  • If the event handler is added using addEventListener, for example

    elem.addEventListener(
        'click',
        function(e){
            return false;
        },
        false
    );

    Then, return false doesn't prevent the default action.

Do all browsers behave like this?

Are there more differences between event.preventDefault() and return false?

Where I can find some documentation (I couldn't in MDN) about return false behaving like event.preventDefault() in some cases?


My question is only about plain javascript, not jQuery, so please don't mark it as a duplicate of event.preventDefault() vs. return false, even if both questions have almost the same title.




What is the different return false and event.preventDefault in javascript?

  • e.preventDefault() prevents default behaviour
  • e.stopPropagation() prevents other event handlers (on parent and child elements) to be fired
  • e.preventImmediatePropagation() prevents other event handlers being fired on the same element
  • return false used to do all of the above

Please note that return false is deprecated, so please try to use the event’s methods.




An easy approach is to leverage this code:

<a href="javascript:void(0);">Link Title</a>

This approach doesn't force a page refresh, so the scrollbar stays in place. Also, it allows you to programmatically change the onclick event and handle client side event binding using jQuery.

For these reasons, the above solution is better than:

<a href="javascript:myClickHandler();">Link Title</a>
<a href="#" onclick="myClickHandler(); return false;">Link Title</a>

where the last solution will avoid the scroll-jump issue if and only if the myClickHandler method doesn't fail.




How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

You need to prevent the default action for the click event (i.e. navigating to the link target) from occurring.

There are two ways to do this.

Option 1: event.preventDefault()

Call the .preventDefault() method of the event object passed to your handler. If you're using jQuery to bind your handlers, that event will be an instance of jQuery.Event and it will be the jQuery version of .preventDefault(). If you're using addEventListener to bind your handlers, it will be an Event and the raw DOM version of .preventDefault(). Either way will do what you need.

Examples:

$('#ma_link').click(function($e) {
    $e.preventDefault();
    doSomething();
});

document.getElementById('#ma_link').addEventListener('click', function (e) {
    e.preventDefault();
    doSomething();
})

Option 2: return false;

In jQuery:

Returning false from an event handler will automatically call event.stopPropagation() and event.preventDefault()

So, with jQuery, you can alternatively use this approach to prevent the default link behaviour:

$('#ma_link').click(function(e) {
     doSomething();
     return false;
});

If you're using raw DOM events, this will also work on modern browsers, since the HTML 5 spec dictates this behaviour. However, older versions of the spec did not, so if you need maximum compatibility with older browsers, you should call .preventDefault() explicitly. See event.preventDefault() vs. return false (no jQuery) for the spec detail.




You haven't really included enough of your code for me to be able to figure out what you want to do - but here's an explanation of the terms you asked about:

event.preventDefault()

event.stopPropagation()

event.stopImmediatePropagation()

Are 3 jQuery functions that differ slightly in how they prevent events and handlers from being executed.

  • event.PreventDefault() is for when you want to prevent the default behaviour of an element. For example if it's a <button> it will no longer be clickable and any handlers bound to it or onclick="" code will not be triggered.

    http://api.jquery.com/event.preventdefault/

  • event.stopPropagation() and event.stopImmediatePropagation() are only slightly different. Along with stopping the default behaviour of the element, event.stopPropogation() and event.stopImmediatePropagation() is used when you want to preven an event from bubbling up the DOM tree, also preventing any parent handlers from being notified of the event. If you use event.stopImmediatePropagation() it will not only hault the even from executing and stop it from bubbling up to its parent elements in the dom, but also prevent any future handlers from being called upon that element. For example if it's a <button> it will no longer be clickable and you will not be able to bind future behaviour such as onclick="" at a later time without forcing a refresh of the page.

    http://api.jquery.com/event.stopimmediatepropagation/

    http://api.jquery.com/event.stoppropagation/

return false;

On the other hand is arguably a basic programming convention that exists in many programming langauges and Javascript is one of these languages.

  • Firstly, unlike the jQuery examples, it's not a function. return means to return a value (usually a variable or the output from a function). The second part is just a boolean value false.

    One reason why it might get associated with the above jQuery functions is because it's frequently used in inline html code like

    <a onclick="window.open(this.href); return false;" href="https://some_website.com/">Go To Website</a>

or similarly with <form> elements if you need to prevent the form from being prematurely submitted. An example would be for form validation of incomplete forms, in that case you could do something like this

    function validateForm() {
        var subject = document.forms["contact"]["subject"].value;
        var message = document.forms["contact"]["message"].value;
        var name = document.forms["contact"]["name"].value;
        var email = document.forms["contact"]["email"].value;

        if ( subject == null || subject == "" || subject == " " || message == null || message == "" || message == " " || name == null || name == "" || name == " " || email == null || email == "" || email == " " ) {
            $('#form-incomplete').html('<strong>Please fill out all the fields before sending email</strong>');

            return false;
        }
    }

You often see return false; used this way: as the result of an if conidition (i.e. if (some_condition_is_present) { return false; // i.e. halt your function } and that's definitely what is missing from your code. If i understand you correctly you would be wanting to try something like

    <a class="some_class" href="http://some-other-website.com">WEBSITE LINK</a>

then somewhere else on the page you could have a script like:

    $("a.some_class").on("click", function(e) {
          e.preventDefault();
          // now the link won't go to http://some-other-website.com
          // but you can still bind other behavour to the element such as alert 
          // console log or trigger another function 
    });

or

    $("a.some_class").on("click", function(e) {
          e.stopPropogation();
          // now the link won't go to http://some-other-website.com
          // and the other elements of the DOM aren't aware that it's been clicked
          // but we can still bind other behaviour like we could:
          alert("user not directed to http://some-other-website.com");
    });

or

    $("a.some_class").on("click", function(e) {
          e.stopPropogation();
          // now the link won't go to http://some-other-website.com
          // and the other elements of the DOM aren't aware that it's been clicked
          // but we can't bind other behaviour to the element.
          // If we try:
          alert("user not directed to http://some-other-website.com");
          // it no longer alerts
    });

or

    $("a.some_class").on("click", function(e) {
          if (!foo) {
              return false; // if our variable is undefined or null we can directly exit our function without executing any code
          } else {
              a.href = foo;
              $("a.some_class").trigger("click"); // however, if our variable is defined we use that variable's value to change where the href of the <a> element will redirect the user's browswer
          }
    });



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