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.

  1. 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.

  1. 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.

Summary

There are two simple ways to change the background color of a web page using JavaScript:

  1. Using the style.backgroundColor property.

  2. Using the addEventListener method.

Copyright ©2024 Educative, Inc. All rights reserved