This is one of my favorite “quick-n-dirty” jQuery tricks. If you’re working on a Web site and you need to add rollover effects to links or other images, you can do it pretty simply with this chunk of JavaScript code and some intelligently named image files. First, make sure you include jQuery if you haven’t already:
Now, include this jQuery code somewhere on your site:
Here’s how it works: each image you have that needs to do something when you mouse over it should have two states, “up” (mouse is off of the image) and “over” (mouse is over the image). Each of these stators will be represented by a specific image, i.e., “foo_up.jpg” and “foo_over.jpg”. So, all you need to do is name each of your following that pattern and add a single CSS class to the image itself within your markup:
And you rollover effects will work automatically. Easy as pie.
Clearly, you can change the naming convention to your liking if my implementation doesn’t suit you, but you’ll need to adjust the JavaScript as well.
The principle at work here is one I recall from The Art of Unix Programming by Eric S. Raymond:
Fold knowledge into data so program logic can be stupid and robust.
This approach is perfect for situations like this because you can tell almost immediately if there’s something wrong with your setup: either the image won’t load or the rollover effect doesn’t work. Either way, it’s pretty damn simple to find out where the bump in the road is and fix it.
I know this is a little inside baseball, but I’ve seen countless web pages where this same effect was achieved by doing this kind of crap:
Photo by Darren Hester
The only problem with your hack is that it loads the images on demand - so won’t be as snappy as it could if you pre-loaded them (but then that would require some code up-front to pre-load them, which kind of kills it being a quick hack :) )