tags:

views:

3010

answers:

3

Hello, I have 2 Divs stacked on top of each other.

I need a really simple function that will:

a) Wait for 3 seconds and then b) FadeOut the top Div to reveal the second Div c) Wait 3 seconds again and then d) FadeIn the top Div again e) Loop back again

Can anyone offer any advice?

Many thanks

A: 

if the two divs have ids of "id1" and "id2", and id2 is the upper one then the code would be like:

function fadeIn() {
  $("id2").animate({opacity:0},500);
  setTimeout(fadeOut,3500);
}

function fadeOut() {
  $("id2").animate({opacity:1},500);
  setTimeout(fadeIn,3500);
}

function startAnim() {
  setTimeout(fadeIn,3000);
}

startAnim() starts the animation cycle , which you should call @ the start. Then fadeIn & Out keep animating id2 and setting timeouts for each other. The delay is 3500 , as you wanted 3 seconds of delay (ie. 3000ms) and 500 for the previous animation to complete. This could have been done using a callback on animate , but that's more messy.

Aviral Dasgupta
+1  A: 

Here's an attempt.

function foo() {
    jQuery("#mydiv").animate({opacity: 1.0}, {duration: 3000})
        .animate({opacity: 0}, {duration: 3000})
        .animate({opacity: 0}, {duration: 3000})
        .animate({opacity: 1.0}, {duration: 3000, complete: foo})
}

Note: To pause, just call animate over a property with the same target value as it is right now. The last animate calls the the same function as callback.

PS: Does it cause stack overflow over time?

Chetan Sastry
Thanks Chetan, that's perfect! I really appreciate your help.
Martin
@Martin, mark this as the correct answer!
ScottE
A: 

This attempt uses a small cookbook function wait from jquery.com.

The function doFading assumes the id of the top div to be "a4".

function doFading() {
      $("#a4").wait(3000)
      .fadeOut("slow")
      .wait(3000)
      .fadeIn("slow",doFading);
    }

$.fn.wait = function(time, type) {
        time = time || 1000;
        type = type || "fx";
        return this.queue(type, function() {
            var self = this;
            setTimeout(function() {
                $(self).dequeue();
            }, time);
        });
    };
Panama