JavaScript - 28
JavaScript - 28: Image Slider
Create a simple image slider with Previous and Next buttons.
Your challenge: Store image paths in an array, keep track of the current image, and move backward or forward through the array.
Show the current image
The variable currentIndex stores which image is currently selected.
Use: sliderImage.src = images[currentIndex];
This changes the image shown on the page.
Move forward
For the Next button: (currentIndex + 1) % images.length moves to the next array item.
The % operator makes the slider return to the first image after reaching the end.
Move backward
For the Previous button: (currentIndex - 1 + images.length) % images.length moves backward and wraps to the last image when needed.
After changing currentIndex, call showImage() again.
Try it: Click Next and Previous several times and watch the slider loop between the images.
Good JavaScript habit: Keep the image-changing code inside one function so both buttons can reuse it.
👀 Show Solution
const images = [
"/space-waffles.webp",
"/water-waffles.webp"
];
let currentIndex = 0;
const sliderImage = document.getElementById("sliderImage");
const prevBtn = document.getElementById("prev");
const nextBtn = document.getElementById("next");
function showImage() {
sliderImage.src = images[currentIndex];
}
prevBtn.addEventListener("click", function() {
currentIndex =
(currentIndex - 1 + images.length) % images.length;
showImage();
});
nextBtn.addEventListener("click", function() {
currentIndex =
(currentIndex + 1) % images.length;
showImage();
});
showImage();Each button changes currentIndex, and showImage() updates the image shown in the slider.
