Learning Horizon | For Learners

ASP.NET, SQL SERVER, JQUERY,JAVASCRIPT, WEBSPHERE

Friday 4 September 2015

What Is Chaining In Jquery?

jQuery is an exceptionally incredible framework of JavaScript. With jQuery, we can utilize chaining which intends to chain together different methods in a solitary statement on a single element.

We have been using a solitary statement at once, but now utilizing the chain technique we can bind multiple methods to shorten the code. This way, browsers do not have to look for the same element(s) multiple times.

Advantage of Jquery Method Chaining:

When using chaining technique in jQuery, it means to connect multiple functions to same element/selectors or it allow us to run multiple JQuery functions/commands on same element(s)/selector(s).

Excessive use of selectors will severely slow down your code, because each call to the selector will force the browser to look for it. By combining or "linking" multiple methods, you can greatly reduce the number of times the browser finds the same element without setting any variables. Let's understand the concept with the help of examples.

Implementation of Simple Technique:

    $(document).ready(function () {

            $("#dvDemo").addClass('hor-minimalist-c');
            $("#dvDemo").css('color','red');
            $("#dvDemo").fadeIn('fast');

        });

Implementation of Chaining Technique:

         
$(document).ready(function () {

   $("#dvDemo").addClass('hor-minimalist-c').css('color', 'red').fadeIn('fast');

  });

While chaining, the line of code could turn out to be very long. However, jQuery isn't extremely strict on the syntax structure; you can organize it like you need, including line breaks and spaces.

         
$(document).ready(function () {

   $("#dvDemo").addClass('hor-minimalist-c')
               .css('color', 'red')
               .fadeIn('fast');

  });

Both the codes above will perform same as far as functionality is concerned but the difference is that second code is shorter and faster because we have use chaining concept in it. The first technique has a problem and that is JQuery have to find "dvDemo" three times in the whole DOM and then execute the functions attached to it.

No comments:

Post a Comment

Please do not enter spam links.