Home >Web Front-end >JS Tutorial >How Can I Change a Webpage's Background Color with JavaScript?

How Can I Change a Webpage's Background Color with JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-19 05:09:021006browse

How Can I Change a Webpage's Background Color with JavaScript?

Altering Webpage Background Color via JavaScript

This article explores a swift method for changing the background color of a webpage by utilizing JavaScript.

Solution

To modify the background color, you can work with the JavaScript property document.body.style.background. Here's how:

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

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

This function takes a color parameter ('red' in this example) and assigns it to the background property. The event listener ensures the function executes when the page loads.

Note: It's important to consider your page's structure. If you're utilizing a DIV container with its own background color, you need to target the background color of that element rather than the document body.

The above is the detailed content of How Can I Change a Webpage's 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