5

It's my second question of the day related to the same problem, so I apologize for that.

I was able to put together a function to "fade out" an element, and it works just fine, my problem is that when I try to reverse it, so the element "fades in" it does not work. I've tried to change the obvious, but I can't understand what I'm doing wrong.

My code so far is as follows:

Given I have a "div" like so:

<div id="test" style="width:200px; height:200px; display:block; opacity:1; background-color:red;"></div>

The JavaScript function that I'm using to fade it out is:

var getElement = document.getElementById('test');
function fadeOut(elem, speed){
if(!elem.style.opacity){
    elem.style.opacity = 1;
}
var desvanecer = setInterval(function(){
    elem.style.opacity -= .02;
    if(elem.style.opacity < 0){
        clearInterval(desvanecer);
    }
}, speed / 50);
}
fadeOut(getElement, 500);

Could somebody take a look at this and let me know what I'm doing wrong, all I want to do is "FADE IN" an element to an opacity equal to "1".

By the way, I can't use jQuery, however I'm eager to learn this way.

Thanks

My attemp to reverse the function is as follows:

var getElement = document.getElementById('test');
function fadeIn(elem, speed){
if(elem.style.opacity){
    elem.style.opacity = 0;
}
var desvanecer = setInterval(function(){
    elem.style.opacity += .02;
    if(elem.style.opacity > 1){
        clearInterval(desvanecer);
    }
}, speed / 50); 
}
fadeIn(getElement, 500);
3
  • 2
    This will not work in any version of IE. Commented Apr 23, 2010 at 0:39
  • Can you show us your fade in code? Commented Apr 23, 2010 at 0:40
  • I will add my "fadeIn" code at the top Commented Apr 23, 2010 at 0:47

1 Answer 1

6

setInterval runs in a global scope, so you need to define the timer relative to the window.

You can't concatinate the string value returned from the style property and expect a number- you'll get '0.02.02.02.02'

Coerce a number out of the string, then add the .02.

It will work in some browsers, but IE before 9 needs a different expression to set and read opacity.

function fadeIn(elem, speed){
    if(elem.style){
        elem.style.opacity= '0';
    }
    window.fadetimer= setInterval(function(){
        elem.style.opacity= +(elem.style.opacity)+.02;
        if(elem.style.opacity> 1){
            clearInterval(fadetimer);
        }
    },
    speed);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, I've been struggling for 2 days with this. Not only it works, but the explanation helped me understand what is going on. Many thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.