1

Basically what I need is an easy way to change the background image of a page every 5 seconds and with a fade effect. The problem that I am having is that I want to do this using my main body tag and I have this CSS:

body {
  background: url("images/bg-home.jpg") no-repeat scroll center top #000000;
}

So the cycle needs to change this div to bg-home-1.jpg, bg-home-2.jpg etc... and this will have to be dynamic as each page has a different number of images so I can't use this way of doing it:

  <div id="fading-images"> 
    <img src="img/home-1.jpg"> 
    <img src="img/home-2.jpg"> 
    <img src="img/home-3.jpg"> 
      </div> 
setInterval(function(){
    $('#fading-images:first-child').fadeOut('slow')
     .next('img').fadeIn('slow')
     .end().appendTo('#slideshow');}, 
     4000);

}

Hopefully someone can help me :)

Reina
  • 315
  • 1
  • 6
  • 21

1 Answers1

3

fiddle: http://jsfiddle.net/G3Fyv/3/

html:

<html>
    <body>
        <div id="fader"></div>
        <div id="background" class="img1"></div>
    </body>
</html>

javascript:

$(document).ready(function() {

    var $fader = $("#fader");
    var $bg = $("#background");
    var cur_img = 0;
    var img_num = 5;

    setInterval(function () {
        var next_img = (cur_img === img_num - 1) ? 0 : cur_img + 1;
        $fader.removeClass().addClass("img" + cur_img.toString()).css("display", "block").fadeOut(2000);
        $bg.removeClass().addClass("img" + next_img.toString());
        cur_img = next_img;
    }, 5000);
});

css

.img1 { background-color: red; }
.img2 { background-color: green; }
.img3 { background-color: blue; }
.img4 { background-color: yellow; }
.img5 { background-color: grey; }

.bg_div {
    position: absolute;
    width: 100%;
    height: 100%;
}

#background { 
    z-index: 1; 
    position: absolute;
    width: 100%;
    height: 100%;
}
#fader { 
    z-index: 2;
    position: absolute;
    width: 100%;
    height: 100%;
}
Ilia Choly
  • 18,070
  • 14
  • 92
  • 160
  • this looks like a fantastic solution, I will have a crack at it tonight and let you know how it goes, thanks!! – Reina Jul 20 '11 at 02:59