2

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');
    });
Pavlo
  • 43,301
  • 14
  • 77
  • 113
  • `class` is a reserved word in JS, so your object literal should use a string as a key (i.e. `{'class': 'block'}`). – zzzzBov Dec 09 '13 at 06:22
  • [Reserved Words actually only apply to Identifiers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words#Reserved_word_usage), and property name is an Indentifier. It shouldn't cause any problems by the spec. – Pavlo Dec 09 '13 at 06:26

1 Answers1

3

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').

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • Maybe drop the `queue` then? Just do `append` - `delay` - `addClass`? – Pavlo Dec 09 '13 at 06:22
  • 1
    `addClass` does not add itself to the fx queue. My point is that, without the `delay` function being called, your code is running identically to `$block.appendTo('body').addClass('shifted');`. To make it run the `addClass` after a timeout, you need to have a delay somehow. – zzzzBov Dec 09 '13 at 06:24