0

In my code I dont find the opacity for the div "box", if I call the function toggle it shows zero.

Why doesnt it shows 2 as it should because opacity is 1 and multiplied with 2.

Here is my code: jsFiddle

<html>
<head>
    <style>
        #box {
            background-color:blue;
            width:100px;
            height:100px;
            opacity:1;
        }
    </style>
</head>
<body>
    <div id="box"></div>
    <button onclick="toggle()">Toggle</button>
    <script>
        var faded = false;
        var current = document.getElementById("box").style.opacity *2;
        var toggle = function() {
            document.getElementById("box").innerHTML = current;
        }
    </script>
</body>
</html>
Blundering Philosopher
  • 5,524
  • 2
  • 42
  • 55

2 Answers2

1

By accessing the style property, you only get the inline styles of the element. Your styles are defined using a stylesheet. What you need to use is getComputedStyle. Do note about its compatibility here.

http://jsfiddle.net/ZxRGB/3/

var box = document.getElementById("box");
function toggle() {
    var styles = window.getComputedStyle(box, null);
    var opacity = styles.getPropertyValue('opacity');
    box.innerHTML = opacity * 2;
}

To make it more robust, you can do what this guy did. You can check for the style in the style property, and when it doesn't exist there, check the stylesheets.

Community
  • 1
  • 1
Joseph
  • 113,089
  • 28
  • 177
  • 225
0

Use this

var current = document.getElementById("box");
var style = window.getComputedStyle(current);
var opacity = style.getPropertyValue('opacity') * 2;
document.getElementById("box").innerHTML = opacity;

If you have inline style or add style through javascript you can use .style but adding it through css use getComputedStyle

Check http://jsfiddle.net/raunakkathuria/ZxRGB/1/

Raunak Kathuria
  • 3,105
  • 1
  • 17
  • 25