Jess
Jess

Reputation: 353

JQuery Queue issues

I am having some serious issues making the JQuery queue work. All the defined functions execute at once, so the class change occurs before the animation- we want it to fade out, then change class, THEN fade back in.

function animatePlusMinus(){
    if ($(this).hasClass("ui-icon-minus")) {
        $(this).queue("goPlus",function(next) {
                $(this).fadeOut(500);
                next();
            })
            .queue("goPlus", function (next) {
                $(this).removeClass("ui-icon-minus").addClass("ui-icon-plus").fadeIn(500);
            })
            .dequeue("goPlus");

    } else if ($(this).hasClass("ui-icon-plus")) {
        $(this)
            .queue("goMinus", function (next) {
                $(this).fadeOut(500);
                next();
            })
            .queue("goMinus", function (next) {
                $(this).removeClass("ui-icon-plus").addClass("ui-icon-minus").fadeIn(500);
            })
            .dequeue("goMinus");
    }
}

I could do this simple example with the callback function on fadeOut, however I'd like to expand this logic in a way which would need a proper queue. I also need to learn how to use .queue()!

UPDATE: Here is an JSFiddle

Upvotes: 1

Views: 77

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382324

Right now, you're calling next immediately after having started the fading.

A solution is to pass next as callback to fadeOut:

function animatePlusMinus(){
    if ($(this).hasClass("ui-icon-minus")) {
        $(this).queue("goPlus",function(next) {
                $(this).fadeOut(500, next);
            })
            .queue("goPlus", function (next) {
                $(this).removeClass("ui-icon-minus").addClass("ui-icon-plus").fadeIn(500);
            })
            .dequeue("goPlus");

    } else if ($(this).hasClass("ui-icon-plus")) {
        $(this)
            .queue("goMinus", function (next) {
                $(this).fadeOut(500, next);
            })
            .queue("goMinus", function (next) {
                $(this).removeClass("ui-icon-plus").addClass("ui-icon-minus").fadeIn(500);
            })
            .dequeue("goMinus");
    }
}

But if you're looking in a more generic solution, you'd probably better dive into promises rather than into queues. Here, with jQuery's implementation of promises, you could do

function animatePlusMinus(){
    if ($(this).hasClass("ui-icon-minus")) {
        $(this).fadeOut(500).promise().then(function(){
            $(this).removeClass("ui-icon-minus").addClass("ui-icon-plus").fadeIn(500);
        });
    } else if ($(this).hasClass("ui-icon-plus")) {
        $(this).fadeOut(500).promise().then(function(){
            $(this).removeClass("ui-icon-plus").addClass("ui-icon-minus").fadeIn(500);          
        });
    }
}

Upvotes: 1

Related Questions