Make an array with the images you want to use:
var images = [
"https://www.royalcanin.com/~/media/Royal-Canin/Product-Categories/cat-adult-landing-hero.ashx",
"https://www.petfinder.com/wp-content/uploads/2013/09/cat-black-superstitious-fcs-cat-myths-162286659.jpg",
"https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_March_2010-1.jpg"
]
We retrieve the div
whose background you want to change:
var imageHead = document.getElementById("image-head");
You can now use setInterval
to change the background image url every second (or whatever interval you want):
var i = 0;
setInterval(function() {
imageHead.style.backgroundImage = "url(" + images[i] + ")";
i = i + 1;
if (i == images.length) {
i = 0;
}
}, 1000);
Here's a live example: https://jsfiddle.net/vvwcfkfr/1/
Some improvements using functional programming, ES6 and recursiveness:
const cats = [
"https://www.royalcanin.com/~/media/Royal-Canin/Product-Categories/cat-adult-landing-hero.ashx",
"https://www.petfinder.com/wp-content/uploads/2013/09/cat-black-superstitious-fcs-cat-myths-162286659.jpg",
"https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_March_2010-1.jpg"
]
const node = document.getElementById("image-head");
const cycleImages = (images, container, step) => {
images.forEach((image, index) => (
setTimeout(() => {
container.style.backgroundImage = `url(${image})`
}, step * (index + 1))
))
setTimeout(() => cycleImages(images, container, step), step * images.length)
}
cycleImages(cats, node, 1000)
https://jsfiddle.net/du2parwq/