Why jquery should have a return false statement for a .click function

Example:

$("#testdiv").click( function( )
 {
     $("#testdiv2").show( "slow" );
     return false;  // why is this statement required?
 } );
+3
source share
4 answers

return false; will not allow the anchor tag to perform the default action

jQuery alternative would be preventDefault()

$("#testdiv").click(function(e) {
    e.preventDefault();
    $("#testdiv2").show("slow");
});
+6
source

returning false to the event handler does two things:

  • If you have an anchor tag, this will prevent anchor from linking

  • It will stop the propagation of the event (bubbles). for instance

    < 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, alert("hello")it will not be called when someone clicks the inner div. Return false matches the call

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

A word of warning, this behavior only works with jquery

event.preventDefault () vs. return false

Source: John Resig

+5
source

, . , <a href="#">, . , / , 'href', <a href="#"> javascript.

+1

false jQuery. , . , , , location.hash <a href="#somelocation">click</a>, - click, return false;.

+1

Source: https://habr.com/ru/post/1785796/


All Articles