A Crazy Simple jQuery Hack for Creating Rollovers

Mouse Cursor

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:

http://gist.github.com/456725

Now, include this jQuery code somewhere on your site:

http://gist.github.com/455216

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:

http://gist.github.com/456727

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:

http://gist.github.com/456812

I find that to be a little gross (and extremely obtrusive in terms of markup).

The swapping technique listed above is something I came up with when I did something that I think everybody (myself more than anybody) should do a little more often – think about the problem you’re trying to solve. Once you’ve done that, think about how you might avoid having to solve the same problem again in the future. Not that there’s a whole lot of genius wrapped up in my 10 lines of JavaScript, but I’ve used it at least 20 times in the last year and it’s served me very well.

What parts of your workflow could benefit from a little bit of extra consideration? 

Photo by Darren Hester