0

JFiddler - http://jsfiddle.net/x2Uwg/

So I have a fade function which first fades the image in and then fades it out. I'd like the image to fade in, change and then fade out. The problem is the only way I can get the img to fade out is if I have it in a button like this.

<button class="hide2" onclick="fadeEffect.init('chestImg', 0)">Fade Out</div>

I'd like for it to be something like this

Img is show

User clicks one button

Image fades in, then changes.

Image fades out.

Right now it is like this.

Img is show

User clicks one button

Image fades in, then changes.

User clicks another button

Image fades out.

My fade function looks like so.

var fadeEffect=function(){
return{
    init:function(id, flag, target){
        this.elem = document.getElementById(id);
        clearInterval(this.elem.si);
        this.target = target ? target : flag ? 100 : 0;
        this.flag = flag || -1;
        this.alpha = this.elem.style.opacity ? parseFloat(this.elem.style.opacity) * 100 : 0;
        this.elem.si = setInterval(function(){fadeEffect.tween()}, 20);
    },
    tween:function(){
        if(this.alpha == this.target){
            clearInterval(this.elem.si);
        }else{
            var value = Math.round(this.alpha + ((this.target - this.alpha) * .05)) + (1 * this.flag);
            this.elem.style.opacity = value / 100;
            this.elem.style.filter = 'alpha(opacity=' + value + ')';
            this.alpha = value
        }
    }
}
}();

I call the fade in like so

fadeEffect.init('chestImg', 1);

And the fade out like so

fadeEffect.init('chestImg', 0);

But if I place them in the same function it will not work. Any help?

Community
  • 1
  • 1
user2612619
  • 1,119
  • 3
  • 11
  • 28

2 Answers2

3

When you call both fadeEffect.init('chestImg', 1); and fadeEffect.init('chestImg', 0); in the same function, then both effects are running simultaneously, which I think is leading to your problem. I think that what you need to do is:

fadeEffect.init('chestImg', 1);
setTimeout(function(){fadeEffect.init('chestImg', 0);},20);
hkk
  • 2,069
  • 1
  • 23
  • 48
0

I believe your problem is with binding this. When a function is called from within the clickhandler of a button, this is set to that button node. You can manually set the this object by using the call function

var button = document.getElementById('hide-id');

fadeEffect.init.call(button,'chestImg', 0);

Why write ".call(this)" at the end of an javascript anonymous function?

Community
  • 1
  • 1
actual_kangaroo
  • 5,971
  • 2
  • 31
  • 45