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

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