Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery fade rotate between 3 divs

Tags:

jquery

I'm trying to fade rotate between 3 divs, current code:

$(window).load(function(){
var div1 = $("#apDiv1");
var div2 = $("#apDiv2");

function fade() {
    div1.stop(true, true).fadeIn(2000);
    div2.stop(true, true).fadeOut(2000, function() {
        // swap in/out
        var temp = div1;
        div1 = div2;
        div2 = temp;
        // start over again
        setTimeout(fade, 1000);
    });
}

// start the process
fade(); })

This works great with 2 divs, but is it possible to insert a 3rd one into the rotation ?

I tried like so:

   $(window).load(function(){
var div1 = $("#apDiv1");
var div2 = $("#apDiv2");
var div3 = $("#apDiv3");

function fade() {
    div1.stop(true, true).fadeIn(2000);
    div2.stop(true, true).fadeOut(2000);
    div3.stop(true, true).fadeIn(2000);
    div1.stop(true, true).fadeOut(2000, function() {
        // swap in/out
        var 
        temp = div1
        div1 = div2;
        div2 = div3;
        div3 = div1;
        div1 = temp
        // start over again
        setTimeout(fade, 1000);
    });
}

// start the process
fade(); })

But that just skips it / doesn't work at all.

like image 611
Marius Prollak Avatar asked Dec 12 '22 15:12

Marius Prollak


1 Answers

To be fair if you are going to use more than two divs I would rewrite that function so it will do any amount rather than just three divs

I have assumed that your divs look something like this (I have given them a class of fade with the starting one having a class of current)

<div id="apDiv1" class="fade current"></div>
<div id="apDiv2" class="fade"></div>
<div id="apDiv3" class="fade"></div>

given this structure you can use the following jquery within your window.load:

var divs = $('.fade');

function fade() {
    var current = $('.current');
    var currentIndex = divs.index(current),
        nextIndex = currentIndex + 1;

    if (nextIndex >= divs.length) {
        nextIndex = 0;
    }

    var next = divs.eq(nextIndex);

    next.stop().fadeIn(2000, function() {
        $(this).addClass('current');
    });

    current.stop().fadeOut(2000, function() {
        $(this).removeClass('current');
        setTimeout(fade, 2500);
    });
}

fade();

Example

like image 67
Pete Avatar answered Jan 13 '23 18:01

Pete