Home >Web Front-end >JS Tutorial >How to Change Background Color with JavaScript?

How to Change Background Color with JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 11:40:11551browse

How to Change Background Color with JavaScript?

Changing Background Color with JavaScript

To seamlessly change the background color of a webpage using JavaScript, leverage the convenient document.body.style.background property. Simply assign a desired color value to this property to update the background.

For instance, consider the following example:

function changeBackground(color) {
   document.body.style.background = color;
}

window.addEventListener("load",function() { changeBackground('red') });

This code assigns the color red to the document.body.style.background property once the web page loads, causing the background color to turn red.

Note that this method assumes a standard HTML document structure. If your page incorporates a DIV container with a specific background color, you may need to adjust the code to target the background color of the DIV instead of the entire document body.

The above is the detailed content of How to Change Background Color with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn