I was developing some web recently and ran into a jQuery problem that was new to me. I was using a class selector to fade a group of elements, and using a callback function which would fire after the fade was complete. Something like this:
[note color=#DDD]
1 2 3 4 5 |
$('.myclass').fadeOut('fast', function() { // My Callback }); |
The problem is that I only wanted to the callback function to execute once, but it was executing for each element in the class. Now, this is expected behavior, but it’s not what I wanted, so I had to find a way to get it to only execute one time, after all the animations were finished.
I asked my good friend google about it, and sure enough, he had an answer.
The trick is to use the last() function to target the last item in the group, then use the queue() function to add a callback to the end of that element’s animation. Finally, dequeue() is used to remove the callback once it’s been run.
[note color=#DDD]
1 2 3 4 5 6 7 |
$('.myclass').fadeOut('fast').last().queue(function() { // My Callback $(this).dequeue(); }); |
Brilliant! And I take absolutely no credit for this, all praise goes to happymango.me.uk.