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.backgroundColor
property:
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 addEventListener
method:
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.
There are two simple ways to change the background color of a web page using JavaScript:
Using the style.backgroundColor
property.
Using the addEventListener
method.