views:

30

answers:

3

I have the code below:

    $(document).ready(function() {
  var bgimages=new Array()
  bgImages[0]="bg.jpg"
  bgImages[1]="bg2.jpg"
  //sloppy preload images
  var pathToImg=new Array()
  for (i=0;i<bgImages.length;i++)
  {
    pathToImg[i]=new Image()
    pathToImg[i].src=bgImages[i]
  }

  var i = 0;
  var rotateBg = setInterval(
  function(){
    $('body').css({backgroundImage:'url(' + bgImages[i] + ')'});
      i++;
   }, 9000);
});

I need assistance solving 2 issues:

  1. It will only loop through the images once, what am I missing? I would like it to repeat endlessly.
  2. How can I cross fade the images in?
A: 

First, write that Array declaration as expression:

var bgimages = ["bg.jpg", "bg2.jpg"];

To your questions. It seems your are missing to set back i so check for that in your interval:

var len = bgImages.length; 
var rotateBg = setInterval(function(){
   $(document.body).css({backgroundImage:'url(' + bgImages[i] + ')'});
     if(i < len)
        i++;
     else i = 0;
}, 9000);

document.body is faster than querying for the 'body' tag. I don't think you can fade or crossfade a backgroundimage. At least, not natively.

jAndy
A: 

you can try

function(){
i=i<bgImages.length?i:0;
$('body').css({backgroundImage:'url(' + bgImages[i] + ')'});
      i++;
   }
}

this will reset i to 0 each time it has reached the end of the array

Doga
+1  A: 

You need to ensure you don't index beyond the upper bound of your array.

In your case, a simple bitwise XOR does the job:

i ^= 1;

If you had more elements in your array, a modulo op would do the job:

i++; i %= bgImages.length;

For the crossfade, you might want to consider CSS transitions. There is even an example on the page. However, this is a W3C working draft, and currently only Webkit-based browsers support it. Firefox should support it before end of year. No words on whether IE will support it and when. Nice thing is it's pretty simple to create, no JS required.

Excerpt:

<style type="text/css">
div.fader img { -webkit-transition: all 1s ease-in-out; }
img.swap1, div.fader:hover img.swap2 { opacity: 1.0; }
div.fader:hover img.swap1, img.swap2 { opacity: 0; }
</style>
R. Hill
i++; i %= bgImages.length;Worked like a champ.I will check out the crossfade via CSS, thanks a bunch!