Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between 'event.preventDefault()' vs. 'return false' in JQuery

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 135
    Comment on it

    Hello reader's today i will discuss about "event.preventDefault()' vs. 'return false"

    First, Divs are set to turn red on click, links are set to hide.

    The top div contains the link which runs with e.preventDefault() which means the link will continue the event flow rather then navigating away,

    In the bottom div, the link runs return false. This means that the link will stop the event flow going to the div by hiding the link, hence the div will not receive that click event.

    You can see the below example

    Here is the HTML

     <div id="prevDef" class="parent">
            <div>
                Text Here...
            </div>
            <a href="#">Click me!</a>
            <div>
                I'm a div, with a link. <a href="#">I'm that link</a>
            </div>
        </div>
    
        <div id="retFalse" class="parent">
            <div>
                Text Here...
            </div>
            <a href="#">Click me!</a>
            <div>
                I'm a div, with a link. <a href="#">I'm that link</a>
            </div>
        </div>
    

    Here is the Css

      .parent{
           border:1px solid #000;
           padding:10px;
           margin:10px;
        }
    

    Here is the Code

    //With 'event.preventDefault();'
    
         $("#prevDef div").click(function() {
              $(this).css({
                  "color": "#f00"
              });
          });
    
          $("#prevDef a").click(function(event) { 
              event.preventDefault();
              $(this).hide();
          });
    
    //With 'return false;'
    
          $("#retFalse div").click(function() {
              $(this).css({
                  "color": "#f00"
              });
          });
    
          $("#retFalse a").click(function(e) {
              $(this).hide();
              return false;
          });
    

 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: