A carousel is a good way to practise state and the DOM.
Direct answer
Keep an array of slides and a current index. Show the active slide, hide the others and change the index with next and previous buttons. Wrap around at the ends and give controls clear labels.
HTML
<div class="carousel">
<button id="prev" aria-label="Previous slide">Prev</button>
<img id="slide" src="img1.jpg" alt="Slide 1">
<button id="next" aria-label="Next slide">Next</button>
</div>
JavaScript
const slides = [
{ src: "img1.jpg", alt: "Slide 1" },
{ src: "img2.jpg", alt: "Slide 2" },
{ src: "img3.jpg", alt: "Slide 3" },
];
let index = 0;
const img = document.querySelector("#slide");
function show() {
img.src = slides[index].src;
img.alt = slides[index].alt;
}
document.querySelector("#next").addEventListener("click", () => {
index = (index + 1) % slides.length;
show();
});
document.querySelector("#prev").addEventListener("click", () => {
index = (index - 1 + slides.length) % slides.length;
show();
});
Improve it
- Add dots to jump to a slide.
- Support arrow keys.
- Add swipe on touch devices.
- Avoid autoplay, or let users pause it.
Where Teyro fits
Teyro's Interactive Web Pages with JavaScript course turns this into short lessons you can play in a few minutes a day. It has 37 lessons, and you can start free.
The bottom line
State plus render is a pattern you will use everywhere.


