Dynamic CSS animation

by Joe Gillespie — May 1, 2004

Last month I introduced the concept of 'film-strip' rollovers and promised to show some more examples this time.

You are probably familiar with the term 'Dynamic HTML'. DHTML suffered badly from cross-browser consistency and has more or less fallen by the wayside. Using CSS along with JavaScript gives us ‘Dynamic CSS’ which is a lot more reliable and not too difficult to grasp as soon as you understand the basic principles of how to make CSS boxes, or their contents, move.

The rollover buttons last month moved the background image of a CSS box in discrete steps like the frames of a ciné film using a very simple JavaScript function.

function fsButton(n,y)
    {
    if (document.getElementById)
        {
        var button = document.getElementById("b"+n);
        button.style.backgroundPosition="0px "+y+"px";
        }
    }

The background image uses my Media 22 font and is set to repeat in the x axis – background-repeat: repeat-x; – so it goes on forever. To get it to move, all we have to do is set up a loop that moves the x position to the left by a few pixels at regular intervals like this...

function run()
    {
        if (running)
        {
        clearTimeout(running);
        running = 0;
        }

    running = setTimeout("run()", speed);

    if (document.getElementById)
        {
        x=x-steps;
        var thebox = document.getElementById("sign");
        thebox.style.backgroundPosition=""+x+"px 0px";
        }
    }

Getting the image to scroll smoothy is just a matter of adjusting the balance between the step distance x and the time delay speed. If the steps are too large, the animation will jerk, if they are too small, the movement will be too slow.

In many years of producing multimedia titles, I often had to simulate 'real world' hardware such as video tape decks. Making a rotary control knob or jog-shuttle dial is no mean feat but with film-strip animation, and a bit of image-map jiggery-pokery, you can get a reasonable effect.

Film-strip animation also lends itself well to the production of digital clocks. Just using one vertical image of a set of numerals 0 to 9, it is possible to make a bank of 4 or 6 digits and flick them into the correct position with the usual JavaScript.

I am currently writing a couple of programs to do all the math and automate the generation of multimedia navigation controls. More details here if you are interested.

I should also reiterate that while these techniques work fine in modern browsers, you should consider alternatives styles or pages for those still using legacy browsers on older computers.

Del.icio.us Digg Technorati Blinklist Furl reddit Design Float