Easy Image Tricks - 1
First, you need to create two images. It's usually best to make the second image just a slight variation of the first image. In the example below, I have the word "button" in a graphic. One of the images have a red background, the other one has a blue background. You'll need to upload these images to your web site. (I keep mine in a directory called graphx.)
<img name="button" src="graphx/redbutton.gif" width="200" height="50" alt="a button" border="0">
Notice that I've given the image a name. This is very important, because it lets me identify the image on the page.
This is what it looks like so far:
I have created a second image with a blue background, called bluebutton.gif. (You'll see it in our finished script below.)
OnMouseOver & OnMouseOut
Two popular events are OnMouseOver and OnMouseOut. When you move your mouse pointer over an image, it signals the web browser to check for OnMouseOver code. After you move your mouse pointer away from an image, it signals the web browser to check for OnMouseOut code.
In order to get our image to change on these two events, we'll code them in an anchor tag around the image, just like a link, except the link won't go anywhere in our example. A regular anchor tag would look like something like this:
But... since we don't want the link to go anywhere, well use <a href="#"></a>
We don't want the browser to take the time to download the second image (in this case, the blue image) *after* we move our mouse over it... instead, we want the browser to load it *immediately*. In order to do this, we'll cache (make a copy of the image) on the browser's computer. We can do that like this:
This code tells the web browser to create some space in cache for a new image, and download bluebutton.gif into that space. If you don't understand it completely, that's okay.
Scripting the EventsNow we need to add our OnMouseOver and OnMouseOut code to the anchor tag. It'll look like this:
<a href="#" onMouseOver="button.src=our_image.src;" onMouseOut="button.src='graphx/redbutton.gif';">
In English, this says that when the mouse pointer moves over the link, load whatever is in our_image.src as the new image on the web page in the object (image) we've called button. When the mouse moves away, load the original image again.
(Note: We could have easily pre-loaded the red button, but it was already loaded with the page, so it would have been wasteful to do so. That's why I decided to just use 'graphx/redbutton.gif' in the OnMouseOut code.)
Putting it Together
Now, we need to put it all together. In our HTML file, we need to include the pre-load script, the anchor tag, and the image tag. Here's how it fits together:
Example in Action:
(Be Careful: Don't give two images (or any other objects) the same name. Your scripts won't work correctly.)