In this tutorial we will see how to Change Background Color onclick using JavaScript. The getComputedStyle() method and backgroundColor property is used for this which will change the background color.
Table of Contents
HTML Code
HTML Code is given below, This code contains four span elements with different background colors.
<!DOCTYPE html>
<html>
<head>
<title>Change Background Color onclick using JavaScript</title>
</head>
<body>
<div class="container">
<span id='1' onclick="color(this)" class='color clr1'></span>
<span id='2' onclick="color(this)" class='color clr2'></span>
<span onclick="color(this)" class='color clr3'></span>
<span onClick="color(this)" class='color clr4'></span>
</div>
</body>
</html>
CSS Code
CSS Code is given below, with the help of this code different background colors are assigned to span elements and the main container is centrally aligned.
* {
margin: 0;
padding: 0;
}
body {
display: flex;
height: 100vh;
align-items: center;
justify-content: center;
}
.container {
border: 2px solid #333;
}
.color {
display: table-cell;
width: 50px;
height: 50px;
margin: 0 1px;
cursor: pointer;
border: 2px solid #FFF;
}
.clr1 {
background-color: #9B0FDB;
}
.clr2 {
background-color: #ffea00;
}
.clr3 {
background-color: #04DB53;
}
.clr4 {
background-color: #0F68DB;
}
JavaScript Code
JavaScript Code is given below, In this code we have used getComputedStyle() method and backgroundColor property.
getComputedStyle() method returns the CSS properties and their values of selected element. It is used to read the background color of span elements. style.backgroundColor property returns only inline css properties and their values that is why we have used getComputedStyle() method.
<script>
function color(z) {
var a = getComputedStyle(z);
var b = a.backgroundColor;
document.getElementsByTagName("BODY")[0].style.backgroundColor=b;
}
</script>
Demo
Video Tutorial
Watch video tutorial on How To Change Background Color onclick using JavaScript.