In this tutorial, we will see how to change the background color of the body or a div in a web-page using JavaScript.
Using JavaScript, we can change any CSS property of a website by manipulating the DOM (Document Object Model) property inside the <script />
tag.
In this article, we will create a function that will change the background of the body/div based on the color value that is passed to the function as an argument.
Let’s see the example with its codes.
Change background color of the body using JavaScript
To change the background color of the body of an entire webpage, we need to modify the JavaScript Property : document.body.style.background
.
So to change the background, we just need to assign a color to it:
document.body.style.background = "red"
However, if you want to change the background color dynamically we have to create a function and pass the color value that we want.
So let’s create a function that will change it with click of a button.
HTML:
<body>
<h1>
Change background color using JavaScript
</h1>
<div class="button">
<button onclick="chngBackground('red')">red</button>
<button onclick="chngBackground('green')">green</button>
<button onclick="chngBackground('yellow')">yellow</button>
</div>
<script src="script.js"></script>
</body>
Script:
function chngBackground(color) {
document.body.style.background = color;
}
In the above code, we have added a click event to all the buttons. When we click the button, it runs the function (chngBackground()
) and it changes the color of the background according to the color value that is passed to the function.
Demo :
Change background color of specific div
Just like document.body which select the <body>
tag, we can also select specific element from a webpage using JavaScript.
To select a specific <div>
in a HTMl web-page we can use: getElementById() or getElementsByClassName().
However, the most recommanded approach is to use getElementById()
because it helps to select a single specific element from a web-page.
In the example, we will change the background of a <div>
element with id=”box”.
Html:
<body>
<h1>
Change background color of the div
</h1>
<div class="button">
<button onclick="chngBackground('red')">red</button>
<button onclick="chngBackground('green')">green</button>
<button onclick="chngBackground('yellow')">yellow</button>
</div>
<div>
<div id="box">
Change background of this div
</div>
</div>
<script src="script.js"></script>
</body>
Script:
function chngBackground(color) {
const box = document.getElementById("box");
box.style.background = color;
}
Here we have selected the <div>
with id=”box” using getElementById() and then changed it background according to the color that is passed to the function when the button is clicked.
Demo:
Related Topics:
Change Text Color Using JavaScript With Example
Check If A HTML Checkbox Is Checked Using JavaScript