John T
John T

Reputation: 1078

How do I cycle the background-url of a div through several images?

I've read through a few similar questions but can't find an answer to my specific problem.

My html is:

<div id="top-area">
  <div class="container">

    // Show title of website here

  </div>
</div>

My css is: #top-area { background-image: url("http://example.com/images/bg.jpg"); }

I would like to have the background of my div fade between up to 5 images.

I've tried defining a #top-area2 and #top-area3 in css and then doing this in jQuery:

$("#top-area").attr("id","top-area2");

But that doesn't give the effect I'm looking for. All the other examples I've found seem to point towards filling the div with hidden images and then revealing them one by one but this doesn't give me the background-image behaviour I'm looking for.

Is this possible? Thanks.

Upvotes: 1

Views: 4464

Answers (2)

Rob M.
Rob M.

Reputation: 36511

This will crossfade and cycle through an array of images:

var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'],
    index  = 0,
    $top   = $('#top-area');

setInterval(function() {
   $top.animate({ opacity: 0 }, 500, function() {
     $top.css('background-image', 'url('+images[++index]+')');
     $top.animate({ opacity: 1 }, 500, function() {
       if(index === images.length) index = 0;
     });
   });
}, 6000);

Demo

Upvotes: 3

isherwood
isherwood

Reputation: 61056

I'd put the image URLs in an array:

var backgrounds = [
   '/img-one.jpg',
   '/img-two.jpg',
   ... 
];
var i = 0;

Then use an interval function to loop through them, updating the CSS:

setInterval(function() {
    $('#top-area').css('background-image', 'url(' + backgrounds[i] + ')');

    i++;

    if (i == backgrounds.length) {
        i = 0;
    }
}, 1000);

Upvotes: 1

Related Questions