Reputation: 742
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
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
Reputation: 1228
There are three things you'll need (two of which have been mentioned by other answers):
setInterval()
, to fire off a handler function every X seconds.document.body
, which gets you a direct reference to the DOM object for the body
element.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
Reputation: 82614
check out setInterval
setInterval(function () {
document.body.style.backgroundImage = new_image;
}, 3000);
Upvotes: 0