Start learning free

LESSON 154 OF 161 · FRONTEND: INTERVIEW QUESTIONS

Image Carousel in JavaScript

Practice

A carousel shows one item of a list at a time, with buttons to move through it. All it needs in state is one number: the index of the item on show. Next adds 1 and Previous takes 1, and at the ends it wraps around: after the last image comes the first, and before the first comes the last.

The % operator, the remainder of a division, does the wrapping. For example, a light that cycles through 3 colors:

const COLORS = ["red", "yellow", "green"];
setColor((color + 1) % COLORS.length);  // 0, 1, 2, 0, 1, …

Going back needs care: in JavaScript, -1 % 3 is -1, not 2, and a list has nothing at index -1. Add the length before the % so the number never goes below 0. The starting code has the five images in IMAGES, the index state, and five dot buttons, "Show image 1" to "Show image 5", that don't do anything yet.

The check clicks through the carousel, and your page must answer:

> open the page         →  image: A blue mug on a wooden table
                            text: Image 1 of 5, dot 1 (current)
> click "Next"          →  Image 2 of 5, A notebook with a red cover
> click "Previous"      →  Image 1 of 5
> click "Previous"      →  Image 5 of 5, A small plant in a green pot
> click "Next"          →  Image 1 of 5
> click "Show image 4"  →  Image 4 of 5, A black pen, dot 4 (current)

Your task: show "Image … of 5" under the image, write next and previous so they wrap at both ends, add the Previous and Next buttons, and make each dot mark itself current and jump to its image.


Assignment
Follow the Coding Tutorial to build the carousel's counter, its Previous and Next buttons, and its dots.


Hint
index counts from 0 and a visitor counts from 1. For Previous, add IMAGES.length to index - 1 before the %. In a dot's onClick, pass a function: don't call setIndex while React draws the page.


STEP 1 OF 9
    Ctrl + Enter to check

    Fe Carousel in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free