How do you implement infinite loop in an image carousel?
Use modulo: currentIndex = (currentIndex + 1) % slides.length for next, and (currentIndex - 1 + slides.length) % slides.length for prev. This wraps around from the last to the first and vice versa.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in How to Build an Image Carousel in an Interview
Create a flex track of images inside an overflow-hidden container. Use translateX to slide. Add next/prev buttons (modulo for infinite loop), dot indicators (click to jump), and auto-play with setInterval. Pause on hover. Add CSS transition for smooth sliding.
Use setInterval(next, 3000) to advance every 3 seconds. Pause on hover with mouseenter (clearInterval) and resume on mouseleave (setInterval again). Clear the interval when the component is destroyed.
Create a dot for each slide. Highlight the active dot. Add a click handler to each dot to jump to that slide: dot.addEventListener('click', () => goTo(index)). Update the active class on each transition.
Still have questions?
Browse all our FAQs or reach out to our support team
