r/JavaScriptTips • • Feb 22 '23

Vanilla JavaScript image carousel 🎠

Post image
15 Upvotes

2 comments sorted by

1

u/Low_Mammoth_9371 Feb 22 '23

Code at text below, full YT tutorial including how to add user controls: https://youtu.be/BGxRao9tkzI

// Get all images (display value initially 'none'):
const images = document.querySelectorAll('#carousel img');

let speed = 3000;
let index = 0;

// Set image to be displayed immediately:
updateContent();

// Start rotating through images at 'speed':
(function startInterval() {
    setInterval(() => {
        index++;
        if (index === images.length) {
          index = 0;
        }
        updateContent();
    },speed);
})();

// Make image at index value visible:
function updateContent() {
   images.forEach(item => item.classList.remove('active'));
   images[index].classList.add('active');
   // 'active' class sets display to 'block'
}

1

u/liluzisquirt_ Feb 26 '23

Interesting I’ll have to test it out