Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a div fade away nicely after a given amount of time

What is the best way to make a <div> fade away after a given amount of time (without using some of the JavaScript libraries available).

I'm looking for a very lightweight solution not requiring a huge JavaScript library to be sent to the browser.

like image 589
Mats Avatar asked Sep 23 '08 21:09

Mats


2 Answers

Not sure why you'd be so against using something like jQuery, which would make accomplishing this effect all but trivial, but essentially, you need to wrap a series of changes to the -moz-opacity, opacity, and filter:alpha CSS rules in a setTimeout().

Or, use jQuery, and wrap a fadeOut() call in setTimeout. Your choice.

like image 158
Steve Paulo Avatar answered Sep 22 '22 01:09

Steve Paulo


Here's some javascript that does it. I found it on a javascript tutorial web site somewhere (which I was unable to find again) and modified it.

var TimeToFade = 200.0;

function fade(eid)
{
    var element = document.getElementById(eid);
    if(element == null) return;

    if(element.FadeState == null)
    {
        if(element.style.opacity == null || element.style.opacity == ''
               || element.style.opacity == '1') {
            element.FadeState = 2;
        } else {
            element.FadeState = -2;
        }
    }

    if(element.FadeState == 1 || element.FadeState == -1) {
        element.FadeState = element.FadeState == 1 ? -1 : 1;
        element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
    } else {
        element.FadeState = element.FadeState == 2 ? -1 : 1;
        element.FadeTimeLeft = TimeToFade;
        setTimeout("animateFade(" + new Date().getTime()
           + ",'" + eid + "')", 33);
    }
}

function animateFade(lastTick, eid)
{
    var curTick = new Date().getTime();
    var elapsedTicks = curTick - lastTick;

    var element = document.getElementById(eid);

    if(element.FadeTimeLeft <= elapsedTicks) {
        element.style.opacity = element.FadeState == 1 ? '1' : '0';
        element.style.filter = 'alpha(opacity = '
            + (element.FadeState == 1 ? '100' : '0') + ')';
        element.FadeState = element.FadeState == 1 ? 2 : -2;
        element.style.display = "none";
        return;
    }

    element.FadeTimeLeft -= elapsedTicks;
    var newOpVal = element.FadeTimeLeft/TimeToFade;
    if(element.FadeState == 1) {
        newOpVal = 1 - newOpVal;
    }

    element.style.opacity = newOpVal;
    element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';

    setTimeout("animateFade(" + curTick + ",'" + eid + "')", 33);
}

The following html shows how it works:

<html><head>
    <script type="text/javascript" src="fade.js"></script>
</head><body>
    <div id="fademe" onclick="fade( 'fademe' )">
        <p>This will fade when you click it</p>
    </div>
</body></html>
like image 34
Graeme Perrow Avatar answered Sep 18 '22 01:09

Graeme Perrow