I am trying to change my background image every 5 seconds. How should I go about this?
window.onload = function () {
function Timer() {
window.setInterval
You can make few changes
1.Not sure from where you are calling Timer function (better if have camelCase)
function Timer() {
window.setInterval("changeImage()", 5000);
}
Instead you can directly use
setInterval(changeImage, 5000);
changeImage
is a callback
2.Could not make out what is this line mean
var bgImg = document.body.style.backgroundImage();
Unsure if can attach a function to style property.
Anyway this below snippet can be useful
window.onload = function () {
// Array of Images
var backgroundImg=["https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRyB57zuc4bms-hDtWMa-4BZvscIlJDm4r7a9WLaO4SAxUvKM-DDA",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQBinSpWOvAtkxjmkf709O3rjH2ObRbWAEn9s0JcWaeL6LMtCbOrQ",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRKY4J2qIFqkuDnABMzeypywbMSZL1cleS8vpySz0KD02wOYORU1g",
"https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRQkdQT0zN0xDVP-VuvwojSbS5dOstX14eZvJCOWNPxKJ5dWTIc"
]
setInterval(changeImage, 5000);
function changeImage() {
var i = Math.floor((Math.random() * 3));
document.body.style.backgroundImage = "url('"+backgroundImg[i]+"')";
}
}
DEMO