0

I am trying to change the opacity of div element every time i call function

<div id="dv" style="width:200px; height: 20px; background-color: blueviolet; opacity: 0.5; ">
<script>    
function opt(){
var d = document.getElementById("dv").style.opacity;
var a = parseFloat(d);
    for(var i=0.5; i == a; i+0.1){
        if(i==1){

            break;
            d = document.getElementById("dv").style.opacity = i;

        }
    }         
}
</script>
<input type="submit" value="submit" onclick="opt()"/>

but it's not working, can somebody help where I am wrong?

Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
mohsin
  • 594
  • 2
  • 8
  • 29

1 Answers1

1

Both the condition and the incrementing part of your for loop are wrong. The proper way to increment i is by saying i+=0.1 not i+1. Also your condition i==a means your loop will only execute while i is equal to a, but if you want the loop to execute until i reaches 1 you should try this

 for(var i=0.5; i <= 1; i+=0.1){
      document.getElementById("dv").style.opacity = i;
} 

EDIT:

Also, it is much easier to use CSS transitions for doing fade in / out. Here's an example with your code

<html>
    <head>
        <!-- Your other head nodes -->
        <style>
            #dv { 
                width:200px; 
                height: 20px; 
                background-color: blueviolet; 
                opacity: 0.5; 
                transition: opacity .5s ease-in-out;
                -moz-transition: opacity .5s ease-in-out;
                -webkit-transition: opacity .5s ease-in-out; 
            }
        </style>
   </head>
   <body>
       <div id="dv"></div>
       <script type="text/javascript"> 
          function opt(){ 
              document.getElementById("dv").style.opacity = 1;
          }
       </script>

       <input type="submit" value="submit" onclick="opt()">
  </body>

mpallansch
  • 1,174
  • 6
  • 16
  • but after 0.7 it's showing 0.799999999999999, 0.899999999999999, 0.999999999999999 – mohsin May 24 '15 at 11:59
  • That's because of the way javascript handles floating point numbers http://stackoverflow.com/questions/3650081/why-does-the-sum-of-2-parsefloat-variables-give-me-an-incorrect-decimal-number If you really want to fix this, say `var a = parseFloat(d).toFixed(1);' documentation of toFixed is here http://www.w3schools.com/jsref/jsref_tofixed.asp – mpallansch May 24 '15 at 12:03