1

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.

2

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

I added images to your fiddle to see it better. There's a delay while they load, unfortunately.
@RobM. This works brilliantly apart from a couple of slight issues. Is there a way to make the next image take over from the last. Instead of the first image fading out to nothing and then the new one fading in? Also, is it possible to only do the animation if the next image has fully loaded? (big ask I know but thought I'd chance my arm in case you knew how to do this). The example you've posted is brilliant. Thanks :-)
@JohnT No problem. You could try CSS animations like this: jsfiddle.net/h2fzvyr5 or checkout this solution: dhirajkumarsingh.wordpress.com/2013/05/05/…
@RobM.Thanks for the links. I'm guessing there's no way of fading in/out at the same time without putting the images inside the div and then selecting them? I'll work on detecting when the images have loaded. Thanks again for the prompt solution, I'll accept your answer :-)
1

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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.