An image slider — also called a carousel — appears on almost every website, from product pages to photo portfolios. Building one teaches you array indexing, CSS transitions, timers, and touch-friendly controls. It is a small project with a very visible result.
What you are building
A row of images where only one is visible at a time, with previous and next buttons, clickable dots for each image, and optional auto-play that pauses when the user hovers over the slider.
The structure
Keep the images in an array and track the current index. Everything else follows from that one number:
<div class="slider"> <img id="slide" src="" alt="Slider image"> <button id="prev">‹</button> <button id="next">›</button> </div> <div class="dots" id="dots"></div> const images = [ "https://picsum.photos/id/1015/800/400", "https://picsum.photos/id/1016/800/400", "https://picsum.photos/id/1018/800/400", "https://picsum.photos/id/1020/800/400", ]; let current = 0; function showSlide(index) { current = (index + images.length) % images.length; document.getElementById("slide").src = images[current]; updateDots(); } document.getElementById("prev").addEventListener("click", () => showSlide(current - 1)); document.getElementById("next").addEventListener("click", () => showSlide(current + 1)); The modulo trick (index + images.length) % images.length makes the slider wrap around in both directions — going back from the first image lands on the last one.
Dots and auto-play
Build the dots from the same array so they never go out of sync, and use setInterval for auto-play:
const dotsContainer = document.getElementById("dots"); images.forEach((_, i) => { const dot = document.createElement("button"); dot.addEventListener("click", () => showSlide(i)); dotsContainer.appendChild(dot); }); function updateDots() { [...dotsContainer.children].forEach((dot, i) => { dot.classList.toggle("active", i === current); }); } let timer = setInterval(() => showSlide(current + 1), 3000); document.querySelector(".slider").addEventListener("mouseenter", () => clearInterval(timer)); document.querySelector(".slider").addEventListener("mouseleave", () => { timer = setInterval(() => showSlide(current + 1), 3000); }); Smooth transitions
A fade is the easiest good-looking transition: put two images on top of each other and animate opacity, or simply add a CSS transition on opacity and briefly fade the image out and back in when the source changes. Avoid slide animations until the fade version works — sliding needs the layout to be exactly right.
What to add next
Add swipe support with touch events, captions for each image, keyboard arrow navigation, or thumbnails under the main image. Each one is a small feature on top of the same current index.