Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are two problems with the function that I can see.</p> <p>First, your <code>if</code> statements both do an assignment rather than a comparison. You are saying <code>if (n=0)</code> (one =, assignment) when you should be saying <code>if (n===0)</code> (three ===, comparison, or you can use two == for a type-converting comparison).</p> <p>Second, using a <code>for</code> loop 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 using <code>setTimeout()</code> - something like:</p> <pre><code>function fadeEffect(element,startValue,target,delay){ element.style.opacity = startValue; if (startValue &lt; target) startValue = Math.min(startValue + 0.1, target); else startValue = Math.max(startValue - 0.1, target); if (startValue != target) setTimeout(function(){fadeEffect(element,startValue,target,delay);}, delay); } &lt;div onMouseOver="fadeEffect(this, 1, 0, 100);" onMouseOut="fadeEffect(this, 0, 1, 100);" id="box"&gt;Menu&lt;/div&gt; </code></pre> <p>Demo: <a href="http://jsfiddle.net/hLQ6y/2/" rel="nofollow">http://jsfiddle.net/hLQ6y/2/</a></p> <p>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 <a href="https://developer.mozilla.org/en/DOM/window.setTimeout" rel="nofollow">.setTimeout()</a> and calling <a href="https://developer.mozilla.org/en/DOM/window.clearTimeout" rel="nofollow">.clearTimeout()</a> 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...</p> <p>UPDATE: Your updated code has introduced new if statements with the same assignment-instead-of-comparison problem. Also it is calling <code>setTimeout()</code> forever - you should do that conditionally as in the answers Pointy and I gave. Also you seem to be relying on the variable <code>i</code> which, 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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload