Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Different way of writing multiple click functions

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 490
    Comment on it

    jQuery make it possible to interact with user by adding events to the web page, It includes many Events Methods like hide(), bind(), blur(), change(), click() and dbclick(). Here in this blog I just want to create one "click" function that includes all the events on a single click. If user wants to add many events to different divs on single click so they can use "On"  method that includes all the events into a single function, here I used "data-content" property also that will store the different values of the div into one variable named "data", then I used "if" condition for executing the different values of data-content the condition is checked into the if statement and then the every condition will be executed one by one.

    This is the simple code that will help you to understand better.

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("body").on("click", ".common", function(){
          var data = $(this).attr("data-content");
           console.log(data);
          if (data=="one") {
              $("#one").hide();
          } 
          if (data=="two"){
               $("#two").animate({left: '250px'});
          }
         if (data=="three" ){
           $("#three").slideToggle();
          }
         
         if (data=="fourth"){
           $("#fourth").fadeOut();
             }
           });
        });
    </script>
    <style>
      .common{border:1px solid #000; background-color: green; color: #fff; padding: 10px 30px; cursor: pointer; width: 300px}
    </style>
    </head>
    <body>
    <div class="common" id="one" data-content="one">Click This paragraph.</div>
    
    <div class="common" id="two" style="background:#98bf21;position:absolute; top:131px;"  data-content="two">Click last paragraph to animate it.</div>
    
    <div class="common" id="three"  data-content="three">Click to slide toggle this paragraph.</div>
    
    <div class="common" id="fourth"  data-content="fourth">Click to fade out paragraph.</div>
    
    </body>
    </html>
    

    Output:- For getting output you can download the below link.

     

 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: