javascriptdomdhtmleffectsfade

Fx on JavaScript: How to fade stuff, etc without frameworks?


I would like to learn how to do fade, and similar effects on JavaScript. I often get answers, like why not use jQuery, Mootools, etc ? Well, I want to learn how stuff works, then I won't mind using any of these frameworks.

I'm currently learning about making changes on the DOM, so, I've read a lot of stuff on this theme. Also, I've read about Reflow, still, I didn't find any cool stuff on Repaint, but, I'll keep searching.

From seeing source files etc, I see a few methods, that I don't know if they've created or are Core methods of JS.

My question is, is there any resource where I can learn all this neat stuff like smooth position change, fading elements trough opacity or whatever, etc?


Solution

  • here's an example that works in firefox and chrome. ie doesn't respect the opacity style.

        var ELEMENT;
        var STEPS;
        var INTERVAL;
        var COUNT;
        var TIMERID;
    
        // 5 * 200ms = 1 second
        STEPS = 5;
        INTERVAL = 200;
    
        function Button1_onclick() {
    
            ELEMENT = document.getElementById("foo");
            COUNT = STEPS - 1;
            TIMERID = setInterval(Fade, INTERVAL);
        }
    
        function Fade() {
    
            ELEMENT.style.opacity = String(COUNT / STEPS);
            COUNT--;
    
            if (COUNT < 0) {
                clearInterval(TIMERID);
                TIMERID = 0;
            }
        }
    

    setInterval and clearInterval are standard js functions. they will execute the given function every x milliseconds. in our case we kill it when we've hit 0 opacity.

    sliding a window is a similar process. you'd set the left/right/top/bottom style instead of opacity.