Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • 'return false' vs 'e.preventDefault()' In jQuery

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 289
    Comment on it

    When we use jQuery event handler, adding return false works same as adding both e.preventDefault and e.stopPropagation on the jQuery.Event object.

    e.preventDefault() will stop the event to occur and return false also prevents that event from propagating the DOM .

    Example:

    $(".submitForm").on("click", function(){
     // some code here .....
     return false;
    });
    $(".submitForm").on("click", function(){
     // another code here ....
    });
    

    When you click on the submitForm the first function will work, but the second function will not run because we have used return false in the first function that stops the calling of second function. If e.stopPropagation() is called, then other function on event handlers of the element won't call. If we write this code by using e.preventDefault() as follows :

    $(".submitForm").on("click", function(e){
     e.preventDefault();
     // some code here .....
    });
    $(".submitForm").on("click", function(){
     // another code here ....
    });
    

    This will call both functions on clicking submitForm.

    In short,

    return false; - calls e.preventDefault(); and e.stopPropagation();

    e.preventDefault(); - Prevents the default behaviour.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: