views:

65

answers:

3

Hey, I'm just wondering how to cycle through a bunch of images, and set them as the background for a div.

What I'm looking to do is: set the first image as the background to a div. Wait X seconds. Set the next image as the background. Wait X seconds … etc. and continue

I've got the following code which works for 1 image.

$(document).ready(function() {
  var source = $(".field-field-background img:first").attr("src");
  $('.field-field-background img:first').remove();
  $('#main-inner').css('background', 'url('+ source +') no-repeat');
});

I'm guessing I need to get an array of the image sources, loop through the array and set it as the background, with a delay somewhere in the loop. Any ideas how I'd do this?

A: 
$(document).ready(function() {
  Cycler={};
  Cycler.src=['path/to/img1', 'path/to/img2', 'path/to/img3'];
  Cycler.cur=0;
  Cycler.cycle=function() {
    if(++Cycler.cur>=Cycler.src.length) {
      Cycler.cur=0;
    }

    $('#main-inner').css('background', 'url('+ Cycler.src[Cycler.cur] +') no-repeat');
    setTimeout(Cycler.cycle, 5000);//5 seconds
  }

  Cycler.cycle();
});
aularon
What's Cycler ?
Mongey
Sorry, `Cylcler` is a namespace (or an ad-hoc object if you want to call it so) I made to gather all those related things, I just forgot to introduce first with `Cycler={};`. Now fixed.
aularon
A: 

try this:

setInterval(function(){
    var source = $(".field-field-background img:first").attr("src");
    $('.field-field-background img:first').remove();
    $('#main-inner').css('background', 'url('+ source +') no-repeat');
},4000);
Moin Zaman
+1  A: 

One of the biggest advantages of jQuery is that it has a very robust plug-in community. Many tasks that you might want to accomplished have been tackled by others before you. Particularly with a common task like this, I would recommend looking for a plug-in first, before trying to reinvent the wheel. Many plug-ins have the advantage of having gone through rigorous testing and multiple versions, to result in a polished product.

The jQuery Cycle plug-in would be a good candidate, if you are looking to do a slideshow type effect. If what you want is to cycle the background, while keeping foreground elements, you might look at something more like this: Advanced jQuery background image slideshow

Ender