JavaScript Change Background Color on Button Click
hardJavaScript + CSSHTML
JavaScript can change any CSS property while the page is open — here, the page's background colour.
The question
Create a button with id "paint". When it is clicked, JavaScript must change the background colour of the <body> to navy.
The code
index.html
<button id="paint">Change colour</button>
<script>
document.getElementById("paint").addEventListener("click", function () {
document.body.style.backgroundColor = "navy";
});
</script>Result
How it works
- 1document.body is the <body> element.
- 2.style.backgroundColor sets its background colour; CSS names with a dash become camelCase in JavaScript.
- 3The change happens inside the click handler, so it runs when the button is pressed.
Common mistakes
- Writing style.background-color — JavaScript reads the dash as a minus sign.
- Forgetting quotes around the colour name.
Now solve a similar question yourself
A new HTML / CSS / JS question every time, checked instantly.
