views:

75

answers:

2

I'm trying to arbitrarily animate images using jQuery and a timer (http://jquery.offput.ca/every/ works as the timer) so as to simulate an animated GIF but allow the animation to be defined within the HTML file (or in a script at the top of the page for repeated use of the same "animated" image).

I've written a specific version in which the frames are fixed: the following code will swap the image(s) with a class of "animate" with /path/to/image/dir/frame1.png and /path/to/image/dir/frame2.png every 300 ms.

<script type="text/javascript" src="jquery.timers.js"></script>
<script type="text/javascript">
    ;(function($){
        $(function() {
            var base_path = "/path/to/image/dir/";
            var on = true;
            $(".animate").everyTime(200, function(i) {
                if(!on) {
                    $(this).attr({src: base_path + "frame1.png"});
                } else {
                    $(this).attr({src: base_path + "frame2.png"});
                }
                    on = !on;
                });
            });
        })(jQuery);
</script>

What I'd like to do is write a generic form of the above, where in an image tag I could put the following

<img src="/path/to/fallback/image.png" class="animate {interval:300, src:[frame1.png,frame2.png]}" alt="animated image" />

and the script could use the parameters passed into the class attribute to determine the duration of each frame and the source image. Initially I only want to alternate between two images, but ideally I'd like to make the src array contain any number of images that would be looped endlessly (i.e. no need for user interaction).

Any ideas how I might implement this? I'm guessing I'm going to need some form of key-value parsing of the class attribute, which may not be semantically correct, so is there another (valid but seldom used) attribute I could use to store the animation properties?

A: 

It looks like what you're basically trying to do is create a new jQuery plugin.

For storing the animation metadata, the jQuery metadata plugin already does what you want and it does support non-class storage locations.

Here's a plugin design pattern that includes instructions for integrating the metadata plugin.

My suggestion is to rework things so that, with that example class attribute, you can enable animation for all cases in the current page with a simple $('img.animate').myAnimationPlugin(); (Naturally, with a more distinctive name)

ssokolow
Thanks, that was what I was looking for. The dataset plugin allows me to make use of html5 data- attributes which are much more useful for this kind of script
zoqaeski
A: 

Why not use some image slider plugin like this: http://nivo.dev7studios.com/

You can set the image switching animation to fade.

gil