Reputation: 1902
html:
<span>hello world!</span>
js: (using callback)
$('span').click(function() {
$(this).animate({
fontSize: '+=10px'
}, 'slow', function() {
// callback after fontsize increased
$(this).text( $(this).text() + ' rolled! ' );
});
});
So that every time SPAN
is click, text 'rolled' appended after font size increased, instead of happening together.
And it can be done by using queue() as well like this:
js: (using queue())
$('span').click(function() {
$(this).animate({
fontSize: '+=10px'
}, 'slow'})
.queue(function() {
$(this).text( $(this).text() + ' rolled! ' );
});
});
I am not sure what is the difference between them. both do the same thing.
Why is queue() better/prefer than using callback, (or why is not ) ? What is special about queue()?
Thanks.
Upvotes: 7
Views: 1156
Reputation: 15810
Using the callback
parameter is exactly the same as using the .queue(callback)
method.
When you supply a callback
to any animation, it just queues the callback the same way as .queue
.
.queue(callback)
is just another way to add a callback separately from your animation.
There's perfectly valid reasons to do so:
$(this).animate(...);
if (shouldDoCallback) {
$(this).queue(...);
}
Upvotes: 0
Reputation: 749
You can put more events (which you specifie else in your code) in the same queue as your animation is put in.
So the callback will be executed immediately after your animation is ready, but in case of using queue() there may be other events in the queue that will be executed first.
The advantage of this behaviour is that no concurrent events (slide up and slide down for example) will be executed at the same time, which would give weird things.
Example:
$('div').click(function() {
$(this).animate({
color: 'green'
}, 'slow'})
.queue(function() {
$(this).text( ' got colored! ' );
});
});
$('span').click(function() {
$(this).animate({
fontSize: '+=10px'
}, 'slow'})
.queue(function() {
$(this).text( ' got bigger! ' );
});
});
If you first click the div and immediately after that the span, now you can be sure that the queue of the div will be executed first, and that when it's ready, the queue of the span will be executed.
In case of a callback, the one belonging to the animation that is ready first, will be executed first. And if they would be ready at the same time, the would both be executed at the same time. Which would result in, in this case, not seeing either the 'got colored!' text or the 'got bigger!' text.
Upvotes: 1