0

I have a fade animation I made in JavaScript but the numbers seem to become NaN and I cannot work out where I went wrong.

My fade animation is in this function:

function transition_opacity(div_id,opacity,direction,fnc){
    var opacity = parseFloat(opacity);
    var IntervId = setInterval(process_transition,30);

    function process_transition(){
    console.log(opacity); //check value as it runs
        if(direction){  
            opacity = opacity +  0.1; //fade back in
        } else {    
            opacity = opacity -  0.1; //fade to transparency
        }
        div_id.style.opacity = opacity;

    if(!direction && opacity < 0.0 || direction && opacity > 1){
            clear();
        }   
    }

    function clear(){
         clearInterval(IntervId);
             if(fnc){ fnc(); }
    }
}

The fade to transparency works fine but fading back up is where it goes wrong... i call the function like this:

var div_id='test';

function display(){
      var opacity = window.getComputedStyle(div_id).opacity;
      transition_opacity(div_id,opacity,1,0); //fade in
  }         

var opacity = window.getComputedStyle(div_id).opacity;                  
transition_opacity(div_id,opacity,0,load); //fade out

The issue is on fade in, the opacity value is not a number from the very start. I don't understand why that is the case when it faded out perfectly fine so surely the opacity should be 0.0?

Sir
  • 8,135
  • 17
  • 83
  • 146

1 Answers1

1
direction & opacity > 1

I'm not all that familiar with javascript but I don't think that does what you want it to.

Edit

I did a quick Google and indeed, & is a bitwise AND in javascript too.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
  • direction true and opacity > 1 exit the interval... opacity max value is 1.0 after all.. – Sir Oct 19 '13 at 01:36
  • & is often `and` in most computer programming languages ;) – Sir Oct 19 '13 at 01:42
  • @Dave && is not the same thing as &. & is an operator that evaluates two binary numbers and the result is 1s where both values had a 1. Your conditional logic is going all wacky there as if you had put direction + opacity > 1 or something like that. – Radiodef Oct 19 '13 at 01:43
  • Yeah my mistake that was a syntax mistake but the NaN still persists with `&&` see edit :) thanks for spotting that though – Sir Oct 19 '13 at 01:45
  • @Dave Maybe it is a floating point problem then? I mean if you are decrementing until it is less than 0 you might not be stopping it at 0. Did you try logging the end value? It might be -0.9999999 or something of the like. http://stackoverflow.com/questions/15583723/javascript-opacity-should-reduce-to-0-and-then-become-negative Also did you try just starting the fade in at 0 instead of grabbing it from the window? Can you make an integer variable to increment and decrement by 1 and then set the opacity as the integer / 10? – Radiodef Oct 19 '13 at 02:09