views:

50

answers:

2

I want to delay things like the css from happening but this method wont work. Any ideas on how I can delay tasks.

$(function() {
    $('.btn').click(function() {
    $('.divOne').animate({"left": "+=400px"}, "fast").delay(800).css("background-color","yellow");
    });
});      
+4  A: 

You can use .queue() to stick it on the default animation (fx) queue, like this:

$('.btn').click(function() {
  $('.divOne').animate({"left":"+=400px"}, "fast").delay(800).queue(function(n) {
    $(this).css("background-color","yellow");
    n(); //call next function in the queue, needed if you animate later!
  });
});

You can test it here, all this does is stick it in the fx queue using .queue(function(n)), the n is the next function in the queue, so we're calling it, for example if you didn't do this and added any animation after it, it just wouldn't run, because the next function or .dequeue() isn't called.

Nick Craver
`n` is not actually the next function in the qeue, it is an anonymous function that calls `dequeue()`, effectively calling the next function in the queue, yes....
gnarf
@gnarf - Matter of semantics I suppose, when you follow the method chain, that anonymous function *is* the next in the queue, effectively, even if not in the queue array itself, it is the *next function* for every other function in the queue :)
Nick Craver
touché ;) I concede...
gnarf
+1  A: 

Maybe use a callback function on the animate. Once the animation is complete use a setTimeout()

$(function() {
    $('.btn').click(function() {
    $('.divOne').animate({"left": "+=400px"},"fast", function() {
        var $elem = $(this);
        setTimeout(function() {
            $elem.css('background-color','yellow');
        }, 800);
    })
});

This might not be syntactically perfect.

elduderino
Don't pass a string to setTimeout! It should look like this instead: `setTimeout(function() { $('.div.one').css('background-color','yellow') }, 800);`
Nick Craver
I updated your answer to not use the evil `eval`ed string argument to setTimeout, and also made it store the animated element in the callback, so you don't have to hunt it down through a jQuery DOM selector again.
gnarf