views:

4136

answers:

3

Hi friends,

I have a big div element at header and there are many text contents and some boxes in the div. and i have a big img as bg for this div, now i need to make a slideshow for this div's background :/

How can I make slideshow for a div's background image?

I researched a lot, but could not find anything :/

Thanks a lot! appreciate!

+1  A: 

One way of doing this is to make an array of background-images:

var bgArr = ["img/bg1.jpg", "img/bg2.jpg"]; //and so on...
function backgroundSlide(i) {
    $("#header").css("background-image", "url("+bgArr[i++]+")");
    if (i == bgArr.length) i = 0;
    var st = setTimeout(arguments.callee(i), 1000);
}
backgroundSlide(0)

This will just loop and loop...

peirix
A: 

You can use the following to change the background image:

$("#mydiv").css("background-image", "url(1.jpg)");

In order to create a slideshow, call it at regular intervals by using settimeout.

kgiannakakis
A: 

Hey guys,

I too was looking for a css background element slideshow, Thanks for your input. I explored your solution with the setTimeout method, however had massive troubles with it (I'm a noob).

I've adapted peirix's solution with a setInterval alternative and came up with this;

var bgArr = ["images/TopImage-01.jpg", "images/TopImage-02.jpg", "images/TopImage-03.jpg" ]; 
var i=0;

// Start the slide show
var interval = self.setInterval("swapBkgnd()", 5000)  

function swapBkgnd() {
 if (i>(bgArr.length-1) ) {
  i=0
  $("#header").css("background-image", "url("+bgArr[i]+")");
 }
 else {
  $("#header").css("background-image", "url("+bgArr[i]+")"); 
 } 
 i++;
};

Now I need to add a fade effect and image preloader and I'll be away. Would be interested to know if there's a tidier way to achieve this.

Cheers,

Dave