I am learning javascript and for that i am creating a simple effects library with fadein fadeout etc functionalities .Everything works ok but it dosent execute the function that i am passing in to execute when the effect is done.
I get the error
element[3] is not a function
my code:
//add the effect
jlqAddEffect(document.getElementById("mainBoard"),"fadeout",10,function(){
alert("done"); //->>>I dont get this executed when the effect is done
});
//EFFECTS
var effectElements=new Array();
function jlqAddEffect(element,type,speed,func)
{
var effect=[element,type,setInterval(function(){jlqUpdateEffect(effect);},speed),func];//->>Here i pass the function in the 3d element of the array
effectElements.push(effect);
jlqInitEffect(effect);
}
function jlqInitEffect(element)
{
if(element[1]=="fadein")element[0].style.opacity=0;
if(element[1]=="fadeout")element[0].style.opacity=1;
}
function jlqUpdateEffect(element)
{
var done=false;
if(element[1]=="fadein"){
if(parseFloat(element[0].style.opacity)<1){
element[0].style.opacity=parseFloat(element[0].style.opacity)+0.01;
}
else done=true;
}
if(element[1]=="fadeout"){
if(parseFloat(element[0].style.opacity)>0){
element[0].style.opacity=parseFloat(element[0].style.opacity)-0.01;
}
else done=true;
}
if(done){
alert("effect done");//->>I get this executed when the effect is done
element[3](); // ->>here it should be calling the function but it gives me the error
clearInterval(element[2]);
effectElements.splice(effectElements.indexOf(element),1);
}
}
EDIT: Ohh i feel silly now .The problem wasn't on the code i posted . I am puting two effect ,one when the page loads and one when it closes in the one when the page loads i wasn't passing an function i was jsut had this
jlqAddEffect(document.getElementById("mainBoard"),"fadein",10);
And since i wasn't passing a function elements[3] wasn't a function...
1 Answer 1
There were two problems when I tested it in Chrome:
You call the
jlqAddEffect()function before theeffectElementsvariable has been initialised to an array, which leads to errors when you try toeffectElements.push(effect);. Easily fixed by moving thejlqAddEffect()call to the end of your code.Your animation never actually completes, because JavaScript's floating point arithmetic (and/or something weird in the handling of the
opacityproperty) prevents the opacity ever getting all the way down to0. It gets down to0.009999999999999247and then gets "stuck". You can fix this by testing whether the opacity is greater than0.01instead of greater than0.
console.log(element[3]);?jlqUpdateEffect(effect)tosetIntervall. But there is noeffectyet.