LAST UPDATED: AUGUST 4, 2021
How to change the background color of a web page dynamically
Answer: Using JavaScript style
property
Generally, we used to set the styling for any HTML element using the CSS properties, and whenever we want changes so we just change the values of the existing properties or add new properties. If we want to change the background color we just have to change the value of the background-color property. But what if we want to change the background color dynamically.
We can also change the background color dynamically using the JavaScript style property. The style property is used to get or set the specific style for an HTML element.
The style property returns the read-only CSSStyleDeclaration object which represents an element's style attribute.
Syntax
The given syntax is used to set the one style for the element.
element.style.property = value
Example: Using style
property
In the given example, we have specified the background color of the p element using the JavaScript style
attribute.
<!DOCTYPE html>
<html>
<head>
<title>Change background color dynamically</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<button onclick="myFunction()">Click Here</button>
<p id="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque eget pellentesque magna. Vestibulum auctor auctor lacinia. Cras ut elit quis augue scelerisque pellentesque vel eu justo. Curabitur mollis viverra nulla, quis mattis justo tincidunt aliquam. Pellentesque eu nulla non enim condimentum gravida. Duis quis auctor dui. Maecenas luctus rhoncus dui vel venenatis. </p>
<script>
function myFunction() {
document.getElementById("para").style.backgroundColor = "yellow";
}
</script>
</body>
</html>
Output
Example: Using window.addEventListener() method
In the given example, we have used the add.EventListner()
method to change the background color dynamically using JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>Change background color dynamically</title>
</head>
<body>
<script type="text/javascript">
function changeBackground(color) {
document.body.style.background = color;
}
window.addEventListener("load",function() { changeBackground('#F5FDB0') });
</script>
</body>
</html>
Output
Conclusion
In this lesson, we have discussed how to change the background color of the element dynamically. JavaScript offers style property that enable us to get or set the inline CSS properties for the element.