Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Jquery return false vs preventDefault

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 215
    Comment on it

    Today we are going to discuss the diffence between return false and preventDefault. We mostly use these scripts but don't know their working so let's go we first discuss the preventDefault.

    A) PreventDefault: it is helpful to stop the default behavior of the browser. Mostly we use it to stop the action of the event such as click,change etc.

    B) return false : it does many things at same time. Firstly it stops the default behavior of the event and also stops the its parent attached events as well. It also stops the callback function whenever called.

    Let us take an example:-

    <html>
    <head>
    <script>
    jQuery(function($){
    
        jQuery('a#myurl1').click(function(){
           console.log('this is anchor link');
           return false;
           alert('this will not be shown');
        });
        jQuery(div).click(function(){
          alert('this is the main div');
        });
        jQuery('myurl2').click(function(){
          console.log('prevent default starting');
          event.preventDefault();
          alert('it will be shown');
        });
    
    });
    </script>
    </head>
    <body>
    <div class="main">
    <a href="http://www.google.com" id="myurl1">return example</a>
    <a href="http://www.yahoo.com" id="myurl2">prevent default example</a>
    </div>
    </body>
    </html>
    

    In above example when we click on the return example link then it will only write the text on console not show the alert box because return false has stopped the function and when we click on the click prevent default example then it will show the both console.log text and alert box.
    I think, it has explained the main concepts.

 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: