How To Create A Looping Html Changing Background Image With Javascript
My JavaScript script, which is meant to continually change the background image of my HTML page, will not do what it is supposed to. function CB() { try { var p = { Pic1:
Solution 1:
You don't need while loop. Just use setInterval (this will call the function every 3 secs) instead of setTimeout (this will call once). Try this
functionCB() {
try {
var p = [
'Images/CoolPic2.jpg',
'Images/CoolPic3.jpg',
'Images/CoolPic4.jpg'
];
var counter = 0;
setInterval(function(){
//document.body.style.backgroundImage = url(p[counter++]);console.log(counter++);
if(counter == 3){
counter = 0;
}
}, 3000)
} catch(err) {
alert(err.message);
}
}
CB();
Solution 2:
This way seams ok:
let i = 1; // = 1 because we want to load first color/image onload const color = ["black", "blue", "brown", "green"]; //change colors to url's
change = () => {
document.body.style.backgroundColor = color[i];//change to background= url(color[i])
i = (i + 1) % color.length;
}
document.body.style.backgroundColor = color[0]; // this will load first collor/imagesetInterval(change, 3000);
based on: LINK
Solution 3:
I guess this might help!!!
var images = [
'Images/CoolPic2.jpg',
'Images/CoolPic3.jpg',
'Images/CoolPic4.jpg'
];
var count = 0;
setInterval(()=> {
body.style.backgroundImage =
"url(" + images[count++] + ")";
if (count == 3) {
counter = 0;
}
}, 3000);
Post a Comment for "How To Create A Looping Html Changing Background Image With Javascript"