Thursday, May 30, 2013

CSS: Start Animating Animated GIF on Hover Event

So this is probably not new. But it's fun to share.

This is not actually "animating" anything. It's about switching images using CSS on mouse hover.
Now that you know, you can either click away or keep reading.


DEMOWoo, a dancing Homer!


To do that, first of all, you need two images. The first image is the static one, preferably the first frame of the GIF. Then the 2nd one is the actual animated GIF.

Upload your images to your file server. Then copy the location of the URLs.

After that, use this CSS background styling.
Let's name the class for the div element as Homer. Set the div with the exact same size as the image.
Here, I have a sweet Homer Simpson image with 165px tall and 140px wide (www.fanpop.com).
Put this styling snippet below in your webpage <head> section or just on top of your blog post's HTML.

CSS (styling)

Change the URLs of the images there with the URLs of your images.

HTML element

And for the element, put it wherever you want the image to show up on your site/blog post.
Anywhere below the styling snippet above.



Basically, that's about it. Fairly easy and fun.

You can use this method to spice up your menu navigation bar and such.
Remember that the <style> element must be placed before (above) the element being styled.

If then you have so many small images, to minimize the http requests, you can combine the images into one big image then implement the CSS image sprites . Or, you can convert your small images to data URI, if the individual file size is considerably small.

The CSS [background] has many separated detailed properties. Those are: [background-color], [background-image], [background-position], [background-size], etc.
In this post, I just showed using the [background] with defined dimensions ([width] and [height]) of the div, so that it would be simpler as starter. You may want to learn more about those separated [background] CSS properties yourself. And tinker the heck out of it. :)
On the example above I also put custom cursor on hover event. Read some more on how to set custom cursor.
As you might be experiencing, there's that "blank" switching to 2nd image moment when using just the CSS method above. You can enhance this by caching the 2nd image via JavaScript or jQuery. I have a post about that, right there.

This is the animating animated GIF post.

No comments:

Post a Comment

Tell me what you think...