Quick & Easy image rollovers using jQuery
I have a navigation bar that I am working with that is made up of images. When you roll over these images we are doing a quick swap for the over image. The reason I am rewriting it is because it was boiler plate Dreamweaver code that uses the 10 year swap image functions and I wanted to do it by hand. Sure the old code works fine but to me its just not very clean and not easy for anyone to understand.
I am fully aware that I could of done a quick search and found a way better solution than this but nobody ever learned anything from cheating so I thought I would give it a try. I built out a fairly standard navigation that looks like this. Now that I have my navigation in place I need to react to the user mousing over the image. All of my images are in a directory called images and to keep it simple I have some easy naming conventions. For each navigation image I have one with _over suffix attached to it. For example, I have a home.png button and a home_over.png for the mouse over state.
It's magic time and I can't believe how easy this was. First we need to include our jquery library and to do that I am using Google's CDN so you can follow along at home. Next we need to loop over ever navigation item we have. To do that we use the following selector to get an array of items back and use the each method to loop over each. Finally for each loop we are going to get the link, the image and the image source. For each link we can add mouse over and mouse out events. In the mouse over method we are doing a simple replace. We are going to replace .jpg with _over.jpg and since the first part of the image name is the same this is all we have to do to swap images. Finally our mouse out just returns the image src to its original state.
As I said there is not much to it but its quite easy and works just fine for what I need it for. If you got some ways to improve this please feel free to chime in. As I said I am no expert and probably could of found something better but nobody ever learns that way. Now maybe I can take this and build a plugin because I have been meaning to write 1. Here is the complete code.
