I’m trying to learn Javascript animations but, as I thinked, it doesn’t work xD.
UPDATED DELETING PASTING MISTAKES
I tried
function click_home()
{
for(i=0;i<=10;i++)
{
setTimeout(setOpacity("div_home",i),200);
}
};
function setOpacity(id,value) {
document.getElementById(id).style.opacity = value/10;
document.getElementById(id).style.filter = 'alpha(opacity=' + value*10 + ')';
};
And HTML:
<td id="button_home" onclick="click_home();"> Home </td>
But obviously is wrong.
What can I do to do this?:)
Thanks to all replies 🙂
Firstly, you’ve got a syntax error in the
forloop (change the,to a;).You need to pass a function to
setTimeout, so it can execute it periodically. What you’re currently passingsetTimeoutis the result of executingsetOpacity("div_home",i)(i.e.undefined).What you’ll also find is you value of
iwill always end up being the last value, because of the scope ofi, to fix this you need to add a new scope level. For a more detailed description on this problem, see How to reference right value of `i` in a callback in a loop?As noted in the comments, you will find all of your timeouts will execute after 200ms.. to get the animation you’ll need to stagger the execution. The simplest way would be to add
ito the delay calculation; i.e.25 * i.I’m not sure why you’re setting the
opacityandfilterto0first in yoursetOpacityfunction; these resets will immediately be set to the values that follow.You should also look at caching the result of
document.getElementById(id).style, as you’re looking it up 4 times (and will be 2 if you remove the unneeded resets described above).