Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Chaining vs Callbacks

For jQuery, what's the difference in the outcome of the following two snippets. Anything? Am I correct that the callback and the second item in the chain are both executed upon completion of the first animation?

$(selector).animate({ opacity: 1 }).animate({ opacity: 0.5 });

vs

$(selector).animate({ opacity: 1}, function()
{
    $(this).animate({ opacity: 0.5 });
});

In what type(s) of situation would I want to use one over the other? Would I only use the latter if I needed to do something more sophisticated or switch to a different selector?

Thanks in advance.

like image 734
technoTarek Avatar asked Feb 16 '12 15:02

technoTarek


People also ask

What is jQuery chaining?

Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.

What is jQuery callback?

jQuery Callback Functions JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors. To prevent this, you can create a callback function. A callback function is executed after the current effect is finished.

What is callback chaining?

chain together a number of functions via callbacks (this is so the first function can use a non-blocking I/O call the other functions are dependent upon), while passing arguments (data) between them, and. without the existing functions having to be modified to be aware of their position in the callback chain.


1 Answers

They are effectively the same, so you'd probably just use the first.

Callbacks (the second version) are for running any arbitrary code that isn't automatically queued.

This includes other jQuery methods like .css() for example, which if not in the callback, will run long before the animation is complete.

// .animate() is automatically queued
$(selector).animate({ opacity: 1 }).animate({ opacity: 0.5 });

// .css() is not automatically queued, so you'd need a callback
$(selector).animate({ opacity: 1 }, function() {
    $(this).css({ opacity: 0.5 });
});

Without the callback...

 // Animation starts ----v
$(selector).animate({ opacity: 1 }).css({ opacity: 0.5 });
 // ...but .css() runs immediately-------------^
 // ...because it isn't automatically added to the queue.
like image 151
user1106925 Avatar answered Nov 12 '22 05:11

user1106925