Color-changing button
This small sample shows how HTML provides a button, CSS styles it, and JavaScript changes its color after a click.
What you will learn
- How to connect a button with an event listener
- How an array can hold a sequence of colors
- Why the current color should be visible to users
Minimal example
<button id="colorButton" type="button">Change color</button>const colors = ['#2463eb', '#15803d', '#c2410c'];
let index = 0;
const button = document.querySelector('#colorButton');
button.addEventListener('click', () => {
index = (index + 1) % colors.length;
button.style.backgroundColor = colors[index];
});Each click advances the index. The remainder operator returns to the first color after the last one.
Common mistakes
- Give the button an explicit
type="button"when it is inside a form and should not submit it. - Keep text contrast high after every color change.
- Do not communicate important information through color alone.