6

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.

MyItchyChin
  • 13,733
  • 1
  • 24
  • 44
Mats
  • 14,902
  • 33
  • 78
  • 110
  • jQuery is 15KB minified and can handle this in one line. I hardly consider that "huge." – John Sheehan Sep 23 '08 at 21:57
  • 15KB is huge, for some values of huge. Why use 15k when 500 bytes is all that's needed? – Adam Davis Sep 23 '08 at 22:01
  • @adam browsers cache the file, so 15k is just for the first use. The cross browser benefits of jQuery far outweight the 14.5k difference. – Chris Sutton Sep 23 '08 at 22:08
  • Although I use a library and don't know why someone wouldn't, the original poster does not want to. Not using a library is his choice and his question is valid regardless of that. JavaScript is a valid language in and of itself. Besides, maybe his client will not allow it, we don't know. – Jason Bunting Sep 23 '08 at 22:25
  • Seriously, you infer just as much about the OP's intentions as the answers that suggest jQuery. Just post a better answer if you have one and let the OP and votes decide. That's how it's supposed to work. – John Sheehan Sep 24 '08 at 04:06
  • Also, jQuery has pre-minified versions already hosted that you can link to which would be highly likely to be already cached. – Sam Hasler Sep 26 '08 at 17:29

6 Answers6

12

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.

Steve Paulo
  • 17,954
  • 2
  • 23
  • 23
  • Another jQuery zealot pushing his fave library on someone that stated they don't want to use one...:P – Jason Bunting Sep 23 '08 at 22:09
  • Why reinvent the wheel? If you don't like jquery, use scriptaculuos, mootools or whatever floats your boat. Reinventing the wheel is silly. – DGM Sep 23 '08 at 22:16
  • 1
    That's not my point - I use a library (MochiKit). My point is that the original poster did NOT want someone to answer with "use library X" - but what happens? Everyone and their mom chimes in with that. Not using a library is his choice and his question is valid regardless. – Jason Bunting Sep 23 '08 at 22:22
  • The OP said they didn't want to use a library but had faulty logic. In that case, I think it's a valid suggestion. If they had a valid reason for not wanting to use a library, that would be different. – John Sheehan Sep 23 '08 at 22:24
  • Understood - the OP may not be aware of the reality of some of the better libraries, but we shouldn't try to read his mind either - maybe he simply phrased his question poorly, aware of how small they are but, for whatever reason, can't use one. – Jason Bunting Sep 23 '08 at 22:29
  • I just think it is kind of funny that whenever a purely JavaScript question is asked on this site, the jQuery zealots immediately answer "use jQuery!" even when it might not be a good fit for the problem. – Jason Bunting Sep 23 '08 at 22:30
  • In my experience, the reality of the answer is that you're not going to find a 'lightweight' solution for fading out an element over time after a delay that'll work cross-browser - the 'reinventing the wheel' concept certainly applies. Also, to be fair, he said he didn't want "a huge library". – matt lohkamp Sep 24 '08 at 00:07
  • Just ignore Jason, at some point in time jQuery hurt his feelings and apparently he likes doing more work than is necessary. – John Sheehan Sep 24 '08 at 04:03
4

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>
Graeme Perrow
  • 56,086
  • 21
  • 82
  • 121
2

These days, I would always use a library for that -- the progress they've made has been phenomenal, and the cross-browser functionality alone is worth it. So this answer is a non-answer. I'd just like to point out that jQuery is all of 15kB.

chryss
  • 7,459
  • 37
  • 46
0

Use setTimeout with the initial time to trigger the fade routine and then use setTimeout with low timer to step through the opacity level of the image until it's gone.

However, jQuery can get down to about 15k and is a one-time download for the client so I wouldn't call it huge.

henriksen
  • 1,137
  • 1
  • 11
  • 24
0

Try the YUI (Yahoo User Interface) Animation library: http://developer.yahoo.com/yui/animation/

Don't reinvent the wheel. Libraries are our friends. :-)

Mike King
  • 261
  • 1
  • 8
  • 1
    He isn't necessarily reinventing the wheel - perhaps he doesn't need everything a library has to offer. If I need a tire, I don't buy an entire car just to get one tire off of it. – Jason Bunting Sep 24 '08 at 03:11
-2

I know you're down on libraries, but I'd recommend taking a look at moo.fx: http://moofx.mad4milk.net/ - I think it's like 3k.

jQuery is pretty damn small too.

Kevin
  • 1,295
  • 2
  • 13
  • 9