Create an image carousel with user controls - OpenJavaScript.info

PHOTO EMBED

Tue Jul 26 2022 22:06:37 GMT+0000 (Coordinated Universal Time)

Saved by @gsinghg19 #javascript

    // Select DOM elements
    const imageContainer = document.getElementById('image-container');
    const images = document.querySelectorAll('img');

    // Create a index counter
    let index = 0;
    
    // Set the function runCarousel to be called
    // every 4 seconds
    let interval = setInterval(runCarousel, 4000);

    function runCarousel() {
        index++ // increase index by 1
        checkOutBoundConditions()
        changeImage() // change image to new index value
    }

    function checkOutBoundConditions() {
        // If index reaches the end, set
        // index to 0 again (recall index
        // starts from 0)
        if(index === images.length) {
            index = 0
        }
        // If index is less than 0, set
        // to 0
        else if (index < 0) {
            index = 0
        }
    }

    function changeImage() {
        // Negative value on translateX shifts images left,
        // so show animates by multiplying the width of an 
        // image by index value
        imageContainer.style.transform = `translateX(${-index * 600}px)`
    }

    const prevBtn = document.getElementById('previous');
    const nextBtn = document.getElementById('next');

    nextBtn.addEventListener('click', () => {
        // reset interval
        clearInterval(interval);
        interval = setInterval(runCarousel, 3000);
        // increase counter by 1
        index++;
        // Run index value through out of bounds 
        // check and then run change image with nex
        // index value
        checkOutBoundConditions();
        changeImage()
    })

    prevBtn.addEventListener('click', () => {
        // reset interval
        clearInterval(interval);
        interval = setInterval(runCarousel, 3000);
        // decrease counter by 1
        index--;
        // Out of bounds check and then change image
        // with new index value
        checkOutBoundConditions();
        changeImage()
    });
content_copyCOPY

https://openjavascript.info/2021/09/02/create-a-rotating-image-carousel-with-user-controls/