Question

I want to append an element to the DOM and then add a class with transition to apply a sliding effect. Currently I'm using setInterval() with delay of 0, otherwise transition won't happen (demo):

var $block = $('<div/>', {class: 'block'});

$('body').append($block);

setTimeout(function () {
    $block.addClass('shifted');
}, 0);

I want to utilise jQuery.queue instead, but with my current approach it doesn't work: appending the element and adding the class happen at once, so no transition is shown.

$('body')
    .append($block)
    .queue(function () {
        $block.addClass('shifted');
    });
Was it helpful?

Solution

If a timeout is required to make the animation happen, then you should add a delay:

$('body')
    .append($block)
    .delay(0)
    .queue(function (next) {
        $block.addClass('shifted');
        next(); //don't forget to dequeue so that the rest of the queue can run
    });

.delay() is really just a convenience method for:

.queue(function (n) {
    setTimeout(n, duration);
});

If you don't call delay (or queue a timeout), the fx queue will execute immediately, which defeats the purpose of queuing $block.addClass('shifted').

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top