
One of the most common JavaScript effects is fading elements and text in and out. Fortunately, it isn’t very difficult to script and doesn’t require a JavaScript framework. This tutorial walks through creating a well-coded standalone fading script.
To begin, let’s create a wrapper object for our functions. It will return two functions: an initialization function and a tween function that will handle the animation. For the init function, we will pass the ID of the element we want to animate as the first parameter. The second parameter will be a toggle (1 or -1) to determine the direction of the fade. The third will be the target (0-100) which will default to 0 or 100 based on the direction.
var fadeEffect=function(){
return{
init:function(id, flag, target){
},
tween:function(){
}
}
}();Now let’s fill in the first function…. here is a breakdown of the lines followed by the code:
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);Next we complete the tween function to update the opacity/alpha on the previously set interval.
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
}And all together now…
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
}
}
}
}();You can call the function like so:
fadeEffect.init('fade', 1, 50) // fade in the "fade" element to 50% transparency
fadeEffect.init('fade', 1) // fade out the "fade" element
Question. I'm using drop down list instead of using buttons. I'm trying to use an if statements so if an user chose 'Yes' the text box will fade out. I use the code above and then call the function inside the if statement if the person click 'Yes'. It didn't work..Nothing happens when i chose 'Yes' .My if logic works because I hidden the text box when an user chose 'Yes' before I added the code above.I need help, please…