Home >Web Front-end >CSS Tutorial >How Can I Change My Webpage's Background Color Using JavaScript?
Changing Background Color with JavaScript
Need a straightforward way to alter the background color of your webpage using JavaScript? Look no further! By tapping into JavaScript's dynamic capabilities, you can easily accomplish this task.
Solution:
To modify the background color, simply change the 'document.body.style.background' property.
Here's a code snippet to illustrate:
function changeBackground(color) { document.body.style.background = color; } window.addEventListener("load",function() { changeBackground('red') });
This function takes a 'color' parameter and applies it to the background property of the 'document.body' element. By placing this function within a 'window.addEventListener("load",...)' block, it's executed upon page load, automatically changing the background color.
Considerations:
Keep in mind that the approach above may require some adjustments based on your page's structure. If your page utilizes a DIV container with a separate background color, you'll need to modify the background color of that DIV rather than the document body.
The above is the detailed content of How Can I Change My Webpage's Background Color Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!