4

I searched for a similar question and someone claimed that return false is similar to event.stopPropagation() and event.preventDefault(), but I have tried the claimed examples and it doesn't work. The code is below:

<ul>
    <li>
        <a href="">baidu.com</a>
    </li>
</ul>

This is the code of html.

ul.addEventListener('click', function(event) {
    alert('ul');
}, false);

li.addEventListener('click', function() {
    alert('li');
}, false);

a.addEventListener('click', function(event) {
    alert('a');
    return false;
}, false);

This is the code of js.

If the return false is both event.stopPropagation() and event.preventDefault().

It will only alert('a'), but finally it alerts three times.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
qiuyuntao
  • 2,314
  • 4
  • 19
  • 24
  • 2
    `return false` does this in jQuery, in vanilla JS you need to use methods of an event. – Teemu Apr 28 '14 at 05:58
  • @Teemu—no jQuery tag, no jQuery in the question text, none in the code, so how do you get jQuery here? – RobG Apr 28 '14 at 06:02
  • @RobG It's the only explanation for "`Somebody says that the return false is both event.stopPropagation() and event.preventDefault().`" – Teemu Apr 28 '14 at 06:04
  • @teemu—see Tim S's answer. – RobG Apr 28 '14 at 13:24

3 Answers3

2
  • 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.

Tim S.
  • 13,597
  • 7
  • 46
  • 72
1

as per your code. if you use event.preventDefault() on "a". it will not redirected to the link if you have any. Default action is prevented.

if you use event.stopPropagation() on "a". Only "a" click event will be fired rest will be stopped.

Do i need to explain about "return false"?

1

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
          }
    });
Community
  • 1
  • 1
DrewT
  • 4,983
  • 2
  • 40
  • 53
  • The functions you list as jQuery functions are copies of DOM functions. jQuery copies most DOM functions so they can be called on jQuery objects like `$(...).click()` copies the DOM [*click*](http://www.w3.org/html/wg/drafts/html/master/editing.html#dom-click) method. See Tim's answer. Also see DOM Events [*preventDefault*](http://www.w3.org/TR/DOM-Level-3-Events/#widl-Event-preventDefault), [*stopPropagation*](http://www.w3.org/TR/DOM-Level-3-Events/#widl-Event-stopPropagation) and [*stopImmediatePropagation*](http://www.w3.org/TR/DOM-Level-3-Events/#widl-Event-stopImmediatePropagation). – RobG Apr 28 '14 at 13:33
  • very detailed answer +1 – James Walker Nov 24 '16 at 01:51