ahsan_khan ahsan_khan - 5 months ago 13
CSS Question

How javscript alert a css value?

Hi there I'm having a problem. I made a box of blue color in HTML/CSS and want javascript to alert the name of color when the box is clicked. Here is my code.`



var clr = document.getElementById("box").style.backgroundColor;
document.getElementById("box").onclick= function() {
alert(clr);
}

<!DOCTYPE html>
<html>

<head>
<title>
</title>
<style>
#box {
height: 100px;
width: 100px;
background-color: blue;
margin: 0px;
display: inline-block;
}

</style>
</head>

<body>
<div id="box" class="box">
</div>
</body>

</html>




Answer

You need to use getComputedStyle(). .style is use to set a new value for target element.

var div     = document.getElementById("box"), // element
    divCSS  = window.getComputedStyle(div), // element CSS 
    bgColor = divCSS.getPropertyValue('background-color'); // property


document.getElementById("box").onclick= function() {
    alert(bgColor);
}
#box{
  height: 100px;
  width: 100px;
  background-color: blue;
  margin: 0px;
  display: inline-block;
}
<div id="box" class="box"></div>

Comments