Skip to Content
Course content

190: Building an Image Carousel/Slider

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think of an image carousel like an old-school slide projector. You have a stack of slides, but the projector only has one slot where the light hits. To see the next image, you don't move the whole projector; you just push the current slide out and slide the next one in. If you hit the end of the stack, you either stop or, more commonly, you flip the whole stack over and start back at the first slide.

In JavaScript, we map this exactly: the "stack of slides" is an array of DOM elements, the "slot" is our CSS visibility, and the "pushing" action is just us incrementing a number (the index) to keep track of which slide is currently active.

Keeping Track of the "Active" Slide

The heart of a slider isn't actually the images—it's a single integer. I always start by defining a currentIndex variable. This is our "source of truth." If currentIndex is 0, we show the first image. If it's 1, the second, and so on.

The mistake I see a lot of developers make is trying to manipulate the DOM directly inside the button click handler. Instead, I want you to separate the logic (changing the number) from the display (updating the UI). We'll create a dedicated function, something like updateCarousel(), that handles the visual heavy lifting.

const slides = document.querySelectorAll('.slide');
let currentIndex = 0;

function updateCarousel() {
  // First, hide every single slide
  slides.forEach(slide => slide.classList.remove('active'));
  
  // Then, only show the one that matches our index
  slides[currentIndex].classList.add('active');
}

Handling the Edge of the Stack

Now, what happens when you're on the last slide and click "Next"? If you just add 1 to the index, you'll end up trying to access an array element that doesn't exist, and your app will crash. This is where we implement the "flip the stack" logic.

I prefer using a simple if statement for readability, though you'll see some people use the modulo operator (%) to do this in one line. For now, let's keep it explicit. If the index exceeds the length of our slides array, we just reset it to zero.

function nextSlide() {
  currentIndex++;
  if (currentIndex >= slides.length) {
    currentIndex = 0; // Loop back to the start
  }
  updateCarousel();
}

function prevSlide() {
  currentIndex--;
  if (currentIndex < 0) {
    currentIndex = slides.length - 1; // Jump to the very end
  }
  updateCarousel();
}

Wiring it to the UI

At this point, the logic is sound, but it's just sitting in memory. We need to hook these functions up to our buttons. Since we've already built the functions to handle the index and the update in one go, the event listeners remain incredibly clean.

One quick tip: make sure your CSS is handling the "active" class. I usually set all slides to display: none and the .active class to display: block. It's the simplest way to ensure only one image is visible at a time without fighting with complex positioning.

document.getElementById('nextBtn').addEventListener('click', nextSlide);
document.getElementById('prevBtn').addEventListener('click', prevSlide);



📋 Practical Task

The Automated Product Showcase

Build a product image slider for an e-commerce page. Your implementation must include the following requirements:

  • Create an HTML structure with at least four product images and "Previous" and "Next" buttons.
  • Implement the index-tracking logic so the carousel loops infinitely (going "Next" on the last image returns you to the first).
  • Challenge: Add a setInterval function that automatically calls your nextSlide logic every 3 seconds, creating an automatic slideshow. Ensure that when a user manually clicks a button, the timer resets so the slide doesn't change immediately after they just clicked.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.