jQuery: Execute a callback once, after a class based animation completes

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] [/note]

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] [/note]

Brilliant! And I take absolutely no credit for this, all praise goes to happymango.me.uk.

Category(s): Googling for Answers, Web Development
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *

* Copy this password:

* Type or paste password here: