I am trying to change the background images of a div, but somehow it runs once and shows the last image and not iterating.
JS
let wrapper = document.querySelector('.wrapper');
let backImages = ['backimage1.jpg', 'backimage2.jpg', 'backimage3.jpg'];
// First way
setInterval(() => {
for (let bg in backImages) {
wrapper.style.background = `url('${backImages[bg]}')`;
}
}, 3000);
// Second way
let changeBg = () => {
for (let bg in backImages) {
wrapper.style.background = `url('${backImages[bg]}')`;
}
};
setInterval(changeBg, 3000);
How can I make it so that it keep iterating over all images endlessly.
I hope this is what you need:
let wrapper = document.querySelector('.wrapper');
let backImages = ['backimage1.jpg', 'backimage2.jpg', 'backimage3.jpg'];
wrapper.style.background = `url('${backImages[0]}')`;
let startIndex = 0;
setInterval(() => {
startIndex = startIndex + 1;
if (startIndex == backImages.length) {
startIndex = 0;
}
wrapper.style.background = `url('${backImages[startIndex]}')`;
}, 3000);
<div class="wrapper"></div>
Ah, this is because he function is doing the forloop all at once.
Start function after 3 seconds.
Do ForLoop
Change 1
Change 2
Change 3
Then Apply.
You'll want to have an iteration outside of that.
let wrapper = document.querySelector('.wrapper');
let backImages = ['backimage1.jpg', 'backimage2.jpg', 'backimage3.jpg'];
//Set a cycle count, and get the max number in your array.
var bgCycleCount = 0;
var bgCycleMax = backImages.length;
setInterval(() => {
//Apply the BG for the current array position.
wrapper.style.background = `url('${backImages[bgCycleCount]}')`;
if(bgCycleCount == bgCycleMax) {
bgCycleCount = 0; //Reset if you've reached the end
} else {
bgCycleCount++; //If not the end, increment the array position
}
}, 3000);
In both the case you are re starting to run the loop from the beginning.
let wrapper = document.querySelector('.wrapper');
let backImages = ['https://www.thespruce.com/thmb/2fz1zlPNq7cj7QkLAtKdqYrKvs0=/3704x2778/smart/filters:no_upscale()/the-difference-between-trees-and-shrubs-3269804-hero-a4000090f0714f59a8ec6201ad250d90.jpg',
'https://www.sciencenewsforstudents.org/wp-content/uploads/2020/04/1030_LL_trees-1028x579.png', 'https://m.media-amazon.com/images/I/71WcZqPYToL._SL1200_.jpg'
];
let count = 0;
setInterval(() => {
wrapper.style.background = `url('${backImages[count]}')`;
count = count === backImages.length - 1 ? 0 : count + 1;
}, 3000);
.wrapper {
width: 500px;
height: 500px;
border: 1px solid red;
}
<div class='wrapper'></div>