3

Example:

$("#testdiv").click( function( )
 {
     $("#testdiv2").show( "slow" );
     return false;  // why is this statement required?
 } );
cdhowie
  • 158,093
  • 24
  • 286
  • 300
dave
  • 14,991
  • 26
  • 76
  • 110

4 Answers4

6

return false; will prevent the anchor tag from doing its default action

a jQuery-alternative would be to preventDefault()

$("#testdiv").click(function(e) {
    e.preventDefault();
    $("#testdiv2").show("slow");
});
hunter
  • 62,308
  • 19
  • 113
  • 113
  • It is not really a *jQuery* alternative. It is normal method of the `event` object (of course jQuery tweaks it a little bit to make it cross-browser compliant). – Felix Kling Jan 16 '11 at 23:02
  • I guess that the events share the same method, but in name only. I 1/2 agree, but I see your point. – hunter Jan 16 '11 at 23:48
5

returning false on an event hander does two things:

  1. If you have an anchor tag it will prevent anchor from following the link

  2. It will stop event propagation (bubbling). For example

    < div id='outer' onclick="alert('hello')" >  
        < div id='inner'>
            <!-- Your stuff -->
        < /div>
    < /div>
    

    and

    $("#inner").click(function(event){
        // Your code
        return false
    })
    

If your function returns false the alert("hello") wont get called when someone clicks the inner div. Returning false is the same as calling both

event.preventDefault();
event.stopPropagation();

A word of warning, this behavior only works with jquery

event.preventDefault() vs. return false

Source: John Resig

Community
  • 1
  • 1
1

Without returning, anchor tag will do whatever it normally does. For instance, if you do <a href="#">, it'll scroll to the top of the page. Since some browsers don't treat as special unless/until there's an 'href' property, <a href="#"> is the most common way to make javascript action links.

Kyle Wild
  • 8,845
  • 2
  • 36
  • 36
  • Which is a shame; http://icant.co.uk/articles/pragmatic-progressive-enhancement/#build – Quentin Jan 16 '11 at 21:21
  • It's definitely a shame, but, for instance, most versions of IE don't honor the ":hover" on elements other than `a`, which means either: (1) using `a` even when you don't want to or (2) using more appropriate element types, and adding Javascript events to handle simple style changes. I lean toward (1) for maintainability, even though it pains me to do so. I guess it's the old pragmatism vs. purism problem. – Kyle Wild Jan 16 '11 at 21:29
1

There's no requirement to return false with jQuery's click event handler. It is only required if you want to prevent the default anchor action from taking place. If you want to do manipulation while still allowing the default action to take place, e.g. update location.hash with a new identifier <a href="#somelocation">click</a> and then doing something with the click event, then you wouldn't be required to supply a return false;.

Lance
  • 1,889
  • 14
  • 12