How to change background color in JavaScript
In JavaScript, changing the background color can be done in various ways. In this article, we'll go over two easy methods.
Using the
style.backgroundColorproperty:
In the example below, we switched the background color from black to crimson using the document.body.style.backgroundColor property. This property sets the body element's background color on a web page.
Using the
addEventListenermethod:
By utilizing this method, we can attach an event listener to the button element, which triggers the execution of a function on a button click. The function is responsible for altering the color of the document’s body element from black to crimson using the document.body.style.backgroundColor property.
Summary
There are two simple ways to change the background color of a web page using JavaScript:
Using the
style.backgroundColorproperty.Using the
addEventListenermethod.
Free Resources