Click here to Skip to main content
15,902,198 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need help trimming and correcting my failing div fading script.
Please help.

XML
<html>
<script>
function fader1() {
document.getElementById("myid").style.opacity= a;
}
var a = 100;
do
{
fader1()
}
while (--a);
</script>

<div id="myid">
This is text.
</div>
</html>
Posted

Here's the contents of my fadeElem.js file.

Usage:

JavaScript
mFadeIn(document.getElementById('idOfElementToFade'), nameOfFunctionToCallWhenFadeComplete);
or, if you dont want to do anything when fading is complete, dont supply a callback
JavaScript
mFadeIn( document.getElementById('idOfElementToFade') );
mFadeOut has the same syntax, it just fades in the opposite direction.

JavaScript
var totalTime = 100;        // time in ms
var ANIMATION_STEPS = 10;   // num steps to go from 0% to 100% or 100% to 0%
var ANIMATION_DELAY = totalTime / ANIMATION_STEPS;  // number of ms between steps

function mFadeIn(element, callback)
{
    element.style.opacity = "0.0";
    element.style.display = "block";
    var stepSize = 1 / ANIMATION_STEPS;
    setTimeout(function(){mAnimStep(element,0,stepSize, true, callback)},ANIMATION_DELAY);
}
function mFadeOut(element, callback)
{
    element.style.opacity = "1.0";
    element.style.display = "block";
    var stepSize = 1 / ANIMATION_STEPS;
    setTimeout(function(){mAnimStep(element,0,stepSize, false, callback)},ANIMATION_DELAY);
}

function mAnimStep(element, iteration, stepSize, boolIsFadeIn, callback)
{
    if (iteration < ANIMATION_STEPS)
    {
        if (boolIsFadeIn == true)
            element.style.opacity = (iteration * stepSize);
        else
            element.style.opacity = (ANIMATION_STEPS - iteration) * stepSize;

        iteration++;
        setTimeout(function(){mAnimStep(element,iteration,stepSize,boolIsFadeIn, callback)}, ANIMATION_DELAY);
    }
    else
    {
        element.style.opacity = "";
        if (boolIsFadeIn == false)
            element.style.display = 'none';
        if (!((callback==null)||(callback==undefined)))
        {
            callback();
        }
    }
}
 
Share this answer
 
 
Share this answer
 
v2
I prefer not using the third-party jQuery plugin. Are there Any ways to do this with normal JavaScript?
 
Share this answer
 
Comments
enhzflep 7-Dec-13 4:50am    
Please dont post comments as answers. Use the 'Have a Question or Comment' button that follows a solution instead. In the case of a comment, hover over the comment and click the reply button.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900