Cory
Cory

Reputation: 742

Rotate Background Image of Body by Time

Can someone help me make a simple javascript to get element body so I can alternate its style to change background images every X seconds?

Upvotes: 1

Views: 885

Answers (3)

user912695
user912695

Reputation:

Set a function to switch backgrounds and add an interval to do it. Backgrounds are contained in array bgArr.

bgArr = ['images/bg1.jpg', 'anotherdir/bg2.jpg', 'otherone/bg3.jpg'];
bgCur = 0;
backgroundSwitch = function()
{
    if (bgCur == bgArr.length) bgCur = 0;
    document.body.style.backgroundImage = 'url('+ bgArr[bgCur++]+ ')';
}
window.setInterval(backgroundSwitch, 30000); // Switch every 30 seconds.

Upvotes: 0

azernik
azernik

Reputation: 1228

There are three things you'll need (two of which have been mentioned by other answers):

  1. The builtin function setInterval(), to fire off a handler function every X seconds.
  2. The expression document.body, which gets you a direct reference to the DOM object for the body element.
  3. A function (to be passed to setInterval()) which will switch between images. This will probably require some data structure to remember the list of images to switch between.

For example:

var images = ['./image1.jpg', './image2.jpg'];
var curImage = 0;
function switchImage()
{
    curImage = (curImage + 1) % images.length
    document.body.style.backgroundImage = 'url(' + images[curImage] + ')'
}
window.setInterval(switchImage, numSeconds * 1000);

Upvotes: 2

Joe
Joe

Reputation: 82614

check out setInterval

setInterval(function () {
    document.body.style.backgroundImage = new_image;
}, 3000);

Upvotes: 0

Related Questions