I tried doing a JS fade effect with the setTimeout() function and it appeared to work to some extent, but I can’t seem to figure out what’s wrong with the code below:
<html>
<head>
<title></title>
<script type="text/javascript">
function FadeEffect(n)
{
var i=1;
fade = document.getElementById("box");
if (n===1)
{
fade.style.opacity=i/10;
i++;
setTimeout("FadeEffect(1)",50);
if (fade.style.opacity=1)
{
var i=1;
}
}
else if (n===0)
{
fade.style.opacity=1-i/10;
i++;
setTimeout("FadeEffect(0)",50);
if (fade.style.opacity=0)
{
var i=1;
}
}
}
</script>
<style type="text/css">
#box{
width: 200px;
height: 50px;
border: 1px solid black;
background-color: #ccc;
opacity: 0;
}
</style>
</head>
<body>
<div onMouseOver="FadeEffect(1)" onMouseOut="FadeEffect(0)" id="box">Menu</div>
</body>
</html>
Edit: updated the code with setTimeout() functions.
There are two problems with the function that I can see.
First, your
ifstatements both do an assignment rather than a comparison. You are sayingif (n=0)(one =, assignment) when you should be sayingif (n===0)(three ===, comparison, or you can use two == for a type-converting comparison).Second, using a
forloop to repeatedly change the style isn’t going to fade because the browser doesn’t update the display at the same time as your code is executing – essentially it uses the same thread for display and for JavaScript. So the page will be updated after the function exits. You need to give the browser a chance to update after each iteration by usingsetTimeout()– something like:Demo: http://jsfiddle.net/hLQ6y/2/
EDIT: Note that this code doesn’t cope all that brilliantly if you move the mouse in and out too quickly, i.e., if you trigger the fade in before the fade out has finished. (You can see what I mean in my jsfiddle.) You can solve this by saving the return from .setTimeout() and calling .clearTimeout() if required. Given that I’ve already covered the essence of the question I’ll leave the fine-tuning as an exercise for the reader…
UPDATE: Your updated code has introduced new if statements with the same assignment-instead-of-comparison problem. Also it is calling
setTimeout()forever – you should do that conditionally as in the answers Pointy and I gave. Also you seem to be relying on the variableiwhich, as a local variable, will not retain its value between calls – you could make it a global, but better to manage it as a parameter like I did or as a local variable in an outer function like Pointy did.