Reena Verma
Reena Verma

Reputation: 1685

Loop through array of images as a Carousel

I'm trying to create a multi-item carousel, in pure JavaScript, using zero carousel plugins.

I want to achieve is having a div, which contains 4/5 images. Sitting next to each other. And then when you click a "next" or "prev" button, you can scroll through the images carousel

Here's a codepen so far: https://codepen.io/ReenaVerma1981/pen/KKKZoYV

I'm getting stuck on the last part. I'm not sure, how to loop through my carousel of images.

So far I have just displayed them statically. You can see I am already looping through my array and display each image, in an individual div. In a container carousel div.

    const arrayCarousel = ['https://www.fillmurray.com/g/200/200', 
    'https://www.fillmurray.com/200/200', 
    'https://www.fillmurray.com/200/200', 
    'https://www.fillmurray.com/g/200/200', 
    'https://www.fillmurray.com/200/100'];

    
     for (let i = 0; i < arrayCarousel.length; i++) {
      const imageURL = arrayCarousel[i];
      console.log('imageURL', imageURL);

      const divElement = document.createElement("div");
      const imgElement = document.createElement("img");
      imgElement.src = imageURL;

      divElement.classList.add("item");
      divElement.appendChild(imgElement);
      carouselContainer.appendChild(divElement);
    }
 <section>
        <div class="carousel-container" id="carousel-container">
        </div>
 </section>

Not sure on how to progress with the next part.... dynamically, scrolling through my array of images.

Any tips on how to create a multi-item carousel, using an array of images?

Thanks!

Upvotes: 0

Views: 5098

Answers (2)

Kalesh Kaladharan
Kalesh Kaladharan

Reputation: 1058

This is something I quickly came up with. Might not be a copy paste solution. Just sharing general idea of how you can do it.

Zoom animations should work fine. Slide animation would require working with DOM elements instead of swapping the images

/**
 * Deregisters the carousal when either next or previous
 * button is clicked. On button clicks, deregister and 
 * re-register is required to avoid image change collisions.
 * 
 * Callback is executed which changes the order of images
 * array.
 * 
 * setItem is called to apply the image order changes.
 * 
 * registerCarousal registers a new carousal loop, so that the
 * loop continues forever.
 */
function onButtonClick(callback) {
    if (typeof callback !== 'function') return;

    deregisterCarousel();
    callback();
    setItem();
    registerCarousal();
}

/**
 * Responsible for changing the src on the
 * carousalItems.
 */
function setItem() {
    var img = document.getElementsByClassName('carousalItems');

    for (let i = 0; i < img.length; li++) {
        img.src = images[i];
    }
}

/**
 * Removes the first image and pushes it to the
 * end of the array.
 */
function shiftForNext() {
    let firstItem = images.shift();
    images.push(firstItem);
}

/**
 * Deregisters the existing timer.
 */
function deregisterCarousel() {

    if (timer == null) return;

    clearInterval(timer);
    timer = null;
}

function registerCarousal() {
    // Remove any existing timer.
    deregisterCarousel();

    // Loop every 1.5 seconds and shifts the 
    // images from 0 to length direction.
    timer = setInterval(function () {
        shiftForNext();

        // Responsible for changing the image src
        // on carousal list elements.
        setItem();
    }, 1500);
}

let timer = null;

let images = [
    'https://www.fillmurray.com/g/200/200',
    'https://www.fillmurray.com/200/200',
    'https://www.fillmurray.com/200/200',
    'https://www.fillmurray.com/g/200/200',
    'https://www.fillmurray.com/200/100',
    'https://www.fillmurray.com/200/100',
    'https://www.fillmurray.com/200/100',
];

// Registers the next button click.
document.getElementById('next').addEventListener('click', function () {
    onButtonClick(function () {
        shiftForNext();
    });
});

// Registers the previous button click.
document.getElementById('prev').addEventListener('click', function () {
    onButtonClick(function () {
        // Removes the last element of the images array
        let lastItem = images.pop();

        // And pushes it to the first position.
        images.unshift(lastItem);
    });
});

// Registers the carousal
registerCarousal();

Upvotes: 0

Melchia
Melchia

Reputation: 24234

You could try using setInterval method and loop through your image array:

const arrayCarousel = ['https://www.fillmurray.com/g/200/200', 
'https://www.fillmurray.com/200/200', 
'https://www.fillmurray.com/g/200/200', 
'https://www.fillmurray.com/200/100'];

counter = 0
const setImage = () => {
 document.getElementById("carousel-image").src = arrayCarousel[counter];
 counter = (counter+1)  % arrayCarousel.length;
}

setInterval(setImage, 1000);
  <section>

    <img id="carousel-image" >

  </section>

Upvotes: 1

Related Questions