Colorizing images on :hover with jQuery
On clevis.cz we have black&white images in portfolio. I wanted to colorize them on :hover.
I wanted to do it and had these goals:
- Without styles and/or JavaScript there will be just a gray image.
- I don’t want to create CSS sprite for each image, it’s time consuming and boring.
- I want to use <img> tag for specifying portfolio image in my code.
- I still want to preload both images (black&white and colored versions), I want to avoid blinking.
- I want to fade in and fade out colored version.
I knew I will have to use jQuery, because CSS can’t do this alone.
I begun with code of a portfolio image. Semantically it made sense to me to use new HTML5 elements <figure> and <figcaption>, see html5 doctor for further explanation.
Now I decided that this code is pretty nice and I don’t want to add any anything else just to enable desired effect.
I googled to find how others are solving this. After a while I found this great tutorial on The Art Of Hand Coding. It’s using CSS sprites but it gave me the idea that I can dynamically take url address from <img> element and set it to another element as background.
But I actually needed to change that url a bit to find the right colorized image to the black&white variant.
At first it seemed impossible to me, because I’m not much jQuery expert. But after a quick google search I found this wonderful plugin created by Mark Perkins, which allowed me to change the URL.
After a while I’ve putted together this script:
It loads the right image (colorized version of portfolio images are prefixed with “color-” and generated automatically by a little Automator script) and the image is placed behind the <img> element. The only thing left is now to fade in and to fade out the colored image, which is pretty easy in jQuery and I actually used the code from The Art Of Hand Coding. It works like this: you slowly let the <img> disappeared and then the background of the link is visible.
And that’s it! All 5 goals completed, it works awesome in every browser I tested it in. (from IE6 to the latest Webkit night build). Check it out at clevis.cz/co-delame.
What do you think?