The Digital Research Initiative The University of North Carolina at Chapel Hill ![]() Image Rollovers Perhaps one of the most overused JavaScript tricks on the web, image rollover is also one of the coolest. You might have noticed it on the previous page when you moused over the link or coffee cup. Rollovers take advantage of special commands in JavaScript called event handlers. Basically, when something happens on a page--when it loads, when the mouse moves over a special spot, or when a specific key is pressed--the event handler takes that action and executes the code associated with it. For our image rollover, we're going to use the onMouseOver and onMouseOut event handlers. When the mouse arrow moves over an image or hot spot on the page, the onMouseOver event handler instantly executes its code. When the mouse moves away from the hot spot, the onMouseOut kicks in with it's own code. Try this really basic rollover. This code snippet goes in your <a href="..."> tag.
And here it is in action. Go ahead, touch it.
When you first moused over it, you might have noticed a slight delay. That's the problem with this script. It has to load the new image once you mouseover. That can be a real pain sometimes, especially if you're on a 14.4 or 28.8 modem. But there is a way around that using a trick called pre-caching. This is where it can get a little complicated, but not so much as other scripts (this is actually a lot easier than most of the scripts I had to write for my homepage). Pre-caching is when both images are loaded into memory when you load the page. Then, when you mouseover the cup of coffee, the browser pulls the new picture straight out of memory without having to download it like in the first script. To pre-cache the images, put this script in your <head>.
Besides the pre-caching, what's so awesome about this slew of code is that it tests to see whether or not the user's browser supports JavaScript. The first block of code, if (document.images), checks to see if the browser recognizes objects. If it does, then the rest of the block is executed. If it doesn't, then the browser moves down to the } else { block and executes that code, which only returns null values, meaning nothing happens on the rollover. Now add this to your <a href="..."> tag (don't forget the name="" to the <img src="">; without it the browser doesn't know where to load the new image, spitting up an error box):
In action, there is no delay.
Despite the extreme overuse of this trick on the web, it adds instant credibility to someone's HTML skills. Once you step into the JavaScript arena, you separate yourself from all the HTML hack wannabe's.
|