Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is ok to chain jquery effects, instead of using callbacks

In the jquery documentation is stated that if you want to add a class after an effect is applied on a selection you must use a callback:

// Fade in all hidden paragraphs; then add a style class to them (not quite right)
$( "p.hidden" ).fadeIn( 750 ).addClass( "lookAtMe" );

// Fade in all hidden paragraphs; then add a style class to them (correct with animation callback)
$( "p.hidden" ).fadeIn( 750, function() {
// this = DOM element which has just finished being animated
$( this ).addClass( "lookAtMe" );
});

However, you can chain two effects without needing to use a callback:

$(".something").fadeOut().fadeIn();

Why is that? shouldn't you have to use a callback like this, too:

$( ".something" ).fadeOut( 750, function() {
   $( this ).fadeIn();
});
like image 424
paulquest Avatar asked Jan 27 '26 10:01

paulquest


2 Answers

From my understanding, when you perform an operation like fadeIn/fadeOut what you are doing is creating a request that gets placed on an internal animation queue, which performs the actions in a FIFO manner. Others can detail this more, but as it works like this it doesn't require the use of callbacks.

like image 180
Taplar Avatar answered Jan 29 '26 00:01

Taplar


Callbacks make sense for asynchronous operations. So the callback is if you want something to happen after the fading is complete. In your case, the subsequent chained .addClass() does not wait for the fading to be complete. It happens right away.

like image 44
Trott Avatar answered Jan 28 '26 23:01

Trott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!