I have a bunch of slide divs inside of a wrapper container. As you can see I have two of them set to display: none initially. Every 4000ms I would like to smoothly transition into the next slide. I have tried a few things with set interval in js and no luck.
Here is my code:
body { padding: 0; margin: 0; } .wrapper {} .slide { display: flex; flex-direction: column; flex-wrap: wrap; height: 100vh; } img { outline: solid 5px #fff; } .single img { width: 100%; height: 100%; } .split img { width: 50%; height: 100%; } .quad img { width: 50%; height: 50%; }
<div class="wrapper"> <div class="slide single"> <img src="https://dummyimage.com/3840x2160/000/fff"> </div> <div class="slide split" style="display: none;"> <img src="https://dummyimage.com/3840x2160/000/fff"> <img src="https://dummyimage.com/3840x2160/000/fff"> </div> <div class="slide quad" style="display: none;"> <img src="https://dummyimage.com/3840x2160/000/fff"> <img src="https://dummyimage.com/3840x2160/000/fff"> <img src="https://dummyimage.com/3840x2160/000/fff"> <img src="https://dummyimage.com/3840x2160/000/fff"> </div> </div>
Advertisement
Answer
Explanation of the solution:
Your div with the wrapper
class is used as a container for the sliders, making it easy to retrieve its children and put them into an array.
Now all you need to do is to track the slider that you want to show (via currIndex), display it, and hide the other sliders (so only 1 will be displayed on the screen).
I chose to add a class to the CSS that will hide any element with this class:
.hidden { display: none; }
Every time you call forEach you will show one slider and hide the rest, put this logic inside setInterval
and it will activate every 4000ms
.
let childsArray = Array.from(document.querySelector(".wrapper").children); let currIndex = 0; setInterval(() => { childsArray.forEach((slider, i) => { if (i === currIndex % 3) { slider.classList.remove("hidden") } else { slider.classList.add("hidden") } }) currIndex++; }, 4000)
body { padding: 0; margin: 0; } .wrapper {} .slide { display: flex; flex-direction: column; flex-wrap: wrap; height: 100vh; } img { outline: solid 5px #fff; } .single img { width: 100%; height: 100%; } .split img { width: 50%; height: 100%; } .quad img { width: 50%; height: 50%; } .hidden { display: none; }
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style.css"> </head> <body> <div class="wrapper"> <div class="slide single"> <img src="https://dummyimage.com/3840x2160/000/fff"> </div> <div class="slide split hidden"> <img src="https://dummyimage.com/3840x2160/000/fff"> <img src="https://dummyimage.com/3840x2160/000/fff"> </div> <div class="slide quad hidden"> <img src="https://dummyimage.com/3840x2160/000/fff"> <img src="https://dummyimage.com/3840x2160/000/fff"> <img src="https://dummyimage.com/3840x2160/000/fff"> <img src="https://dummyimage.com/3840x2160/000/fff"> </div> </div> </body> <script src="test.js"></script> </html>