Solution: Colorful button
Challenge what you know about loops and arrays.
We'll cover the following
Colorful button
Let’s create a task using a loop and an array of colors. Upon clicking a button, the background color should rotate through the colors stored in an array ["white"
, "lightblue"
, "lightgreen"
, and "lavender"]
.
Each time the user clicks the button:
The background color changes to the next color in the array.
When the last color is reached, the cycle starts again from the beginning.
You’ll need to use:
An array to hold the colors.
A variable to track which color comes next.
A click event listener.
document.body.style.backgroundColor
to change the background color from JavaScript.
Below are some hints to help you get started:
Hints
1️⃣ Where will we store the list of background colors?→ Use an array like const colors = ["white", "lightblue", "lightgreen", "lavender"];
.
2️⃣ How do you keep track of which color is showing?→ Use a variable (e.g., let currentIndex = 0
) to remember the current position in the array.
3️⃣ What structure helps us loop back to the beginning when we reach the last color?→ Use an if–else
or if
condition to reset the index to 0 when it reaches the end.
4️⃣ How do you apply a color to the background?→ Use document.body.style.backgroundColor = colors[currentIndex];
.
5️⃣ How do you test that it works?→ Use console.log()
to print the current color each time you click.
Find the solution in the widget below:
Get hands-on with 1400+ tech skills courses.