fbpx

9 Mar /Using jQuery.queue() to call Functions Synchronously

Posted by Miguel Lozano

This week I was working on a project that required me to add a css class to an element within a sequence of events. First I wanted to fadeOut() an array of elements, wait a moment, and then add a class to another element.

Because Javascript is asynchronous, on my first attempt everything executed, just not in the order I had anticipated.

Enter jQuery.queue().

This handy little function allows you to pass in a callback with next as a parameter, enabling you to call jQuery and Javascript synchronously.

someElements.fadeOut()
            .delay(200)
            .queue(function(next) {
              otherElements.removeClass('active');
              thisElement.addClass('active');
              next(); // continue to next line
            });
someElements.fadeIn();

Now we can call fadeOut() on someElements, handle adding and removing classes after our delay() and then fade someElements back in.