tags:

views:

52

answers:

2

I am using this code to delay the entrance of an element to the viewable area of the screen, but the first animate is wholly unecessary, other than to start a queue that delay can then delay.

$("#top-message").animate({top: '-500px'},400).delay(1000).animate({top: '0px'},800).delay(3000).animate({top: '-500px'},800);

is there a more sensible way to do it?

+3  A: 

I don't get it. If there's no need for the first .animate(), when why do it? If you just need an extra 400ms, then add it to the first .delay().

Example: http://jsfiddle.net/LFt4k/

$("#top-message").delay(1400).animate({top: '0px'},800)
                 .delay(3000).animate({top: '-500px'},800);

You don't need an initial .animate() to start a queue. The .delay() method will use the default "fx" queue.


EDIT:

The issue you may be having is that if #top-message doesn't have an initial value for top, it will be reported as auto in some browsers. This value is not useful for animations.

To solve this, either give #top-message an initial value in CSS:

#top-message {
    top: -500px;
}

...or in javascript:

$("#top-message").css({top:-500})
                 .delay(1400).animate({top: '0px'},800)
                 .delay(3000).animate({top: '-500px'},800);
patrick dw
if I take it out, the first delay doesn't happen
Mild Fuzz
I am assuming that it isn't delaying because no effects queue has been started.
Mild Fuzz
@Mild Fuzz - But it does delay. See the example. If it isn't delaying, then there's some other issue. For example, if you're trying to delay something like a `.css()`, it won't work without additional steps.
patrick dw
@Mild Fuzz - ...ah, I know what the issue may be. It's not the queue, it is that if you don't have some initial value set for the `top` property of `#top-message`, some browsers report it as `auto`, which isn't use for animations. I'll update.
patrick dw
I am away from my code, so I can't confirm, but I am pretty sure top does have an initial state in the stylesheet, otherwise it would appear before time.
Mild Fuzz
@Mild Fuzz - I'd be curious to know when you get back to your code. It is strange that `.delay()` doesn't work unless it has an `.animate()` *before* it.
patrick dw
aha!! I had neglected to put the 'px' after the 500 in the stylesheet. Now it works!! Woohoo!!
Mild Fuzz
@Mild Fuzz - Glad you got it working. :o) I see I did the same thing in my updated answer too. Fixed.
patrick dw
+1  A: 

How about doing it in a callback ?

$("#top-message").animate({top: '-500px'}, 400, function () {
    $(this).delay(1000).animate({top: '0px'}, 800, function () {
        $(this).delay(3000).animate({top: '-500px'}, 800);
    });
});

Example : http://jsfiddle.net/Avinash/LFt4k/2/

Ninja Dude
is this not just a longer way to do what I already have?
Mild Fuzz