Ali Baig
Ali Baig

Reputation: 11

JS setInterval() firing only once

<html>

<head>
  <script type="text/javascript">
    function topdiv() {
      var z = document.createElement("DIV");
      z.id = "top";
      z.style = "background-color:yellow; width:100%; height:50px; opacity: 1.0";
      z.class = "top";
      document.body.appendChild(z);
    }

    function animateDiv() {
      var d = document.getElementById("top");
      if (d.style.opacity == "0.0") {
        d.style.opacity = "1.0";
      } else {
        d.style.opacity = "0.0";
      }
    }
  </script>
</head>

<body onload="topdiv()">
  <script type="text/javascript">
    var xyz = setInterval(function() {
      animateDiv()
    }, 300);
  </script>
</body>

</html>

I am using setInterval in my code to constantly change the opacity of a div after 30 ms, but the function is only executed once. Can someone please help me fix it?

Upvotes: 0

Views: 81

Answers (2)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107508

Because you're setting the initial opacity with CSS, you would need to look at the computed style. Instead of doing that; set the opacity in code on the element itself.

Just in case the browser does return a string value, coerce it into a Number before the comparison. You can also set the opacity as a number.

Have a look at this:

<html>

<head>
  <script type="text/javascript">
    function topdiv() {
      var z = document.createElement("DIV");
      z.id = "top";
      z.style = "background-color:yellow; width:100%; height:50px; opacity: 1.0";
      z.style.opacity = 1;
      z.class = "top";
      document.body.appendChild(z);
    }

    function animateDiv() {
      var d = document.getElementById("top");
      if (+d.style.opacity == 0) {
        d.style.opacity = 1;
      } else {
        d.style.opacity = 0;
      }
    }
  </script>
</head>

<body onload="topdiv()">
  <script type="text/javascript">
    var xyz = setInterval(function() {
      animateDiv()
    }, 300);
  </script>
</body>

</html>

Upvotes: 0

huan feng
huan feng

Reputation: 8623

change

if (d.style.opacity == "0.0") 

to:

if (d.style.opacity === "0") 

http://plnkr.co/edit/eWFDo9OJrYzK3ahz1EBG?p=preview

Upvotes: 1

Related Questions