Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Chaining in jQuery

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 401
    Comment on it

    Chaining is a technique that allows us to run multiple jQuery commands, one after the other, on the same element. Using chaining we can run multiple jquery methods within a single statement.
    Chaining makes code short and easy to manage and it improves the performance as a browser doesn't need to find the same element again and again.
    To chain an action simply append the action to the previous action. Chaining starts from left to right so the left most is called first and so on.
    Let's understand changing with an example:

    Sample Code 1

    $(document).ready(function(){
    
        $('#mydiv').addClass('myclass');
    
        $('#mydiv').css('color', 'red');
    
        $('#mydiv').fadeIn('slow');
    
    });

     

    Sample Code 2

    $(document).ready(function(){
    
        $('#mydiv').addClass('myclass')
    
              .css('color', 'red')
    
              .fadeIn('slow');    
    
    });

    Both the above sample codes will do the same thing but Sample code 2 is swifter and shorter than Sample code 1 because in sample code 1 jquery will search the entire DOM and find the element and after that executes the attached function on it. But at the time when changing used, then once jQuery has to find the element and all the attached functions will be executed by it one by one
    Chaining can also be used with events in jQuery.

    For example.

    $(document).ready(function() {
    
        $("#mydiv").click(function(e) {
    
            alert("mouse click!");
    
        }).mouseover(function(e) {
    
            alert("mouse over!")
    
        }).mouseout(function(e) {
    
            alert("mouse out!")
    
        });
    
    });
    
    

     

 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: