How do I make an image carousel with JavaScript that changes photos at the exact same time in sync with CSS animations?

Viewed 102

I'm trying to make an image carousel that shows three photos that fade-out and fade-in when they change, but I can't figure out how to make all three images change at once while in sync with the fade-out fade-in animation.

what I thought I would do was have a div containing 3 divs with images. then through js I make an array of all the images I want to use then randomly select a photo. But then the photo can't show up twice in one slide, so I add a condition and another array to check if the photo was already used. Then I swap the images after 5 seconds with setInterval, adding a CSS animation to the main container div.

I'm also open to another way of displaying photos in a randomized order instead of this one.

Full code: https://srcshare.io/?id=60dd3c0ad56829604d39814b

...
               
    let waitFor = 5000;
    let imgs = document.getElementById("wrapper");

    function fadeInOut() {
                        let animation = "fade " + waitFor + "ms linear infinite";
        imgs.style.animation = animation;
    }
    function fadeStop() {

        imgs.style.animation = "";
    }

    let firstImg = document.getElementById('image1');
    let secondImg = document.getElementById('image2');
    let thirdImg = document.getElementById('image3');

    setInterval(function () {

        fadeStop();


        let imgSlots = ["", "", ""];
        let alreadyPicked = [];

        for (let i = 0; i < 3; i++) {

            let slotFull = false;

            while (!slotFull) {


                let sponsor = Math.floor(Math.random() * sponsorList.length);
                if (!alreadyPicked.includes(sponsorList[sponsor])) {

                    imgSlots[i] = sponsorList[sponsor][1];
                    alreadyPicked.push(sponsorList[sponsor]);
                    slotFull = true;
                }

            }

        }
        
            fadeInOut();
            firstImg.src = imgSlots[0];
            secondImg.src = imgSlots[1];
            thirdImg.src = imgSlots[2];

    }, waitFor);



});

</script>
<style>
  /*IMAGE CORNER CURVATURE*/
  img{
    border-radius: 0px;
   
  }
  
/*for sponsorship images*/
.inline{
  display: inline-block !important;
  width: clamp(100px,16vw,350px) !important;
  padding: 0px !important;
  white-space: nowrap !important;
  
}
  .wrapper{
    opacity: 0;
  }


@keyframes fade {
  0%,100%{opacity:0}
  15%,85%{ opacity: 1 }

}
</style>
0 Answers
Related