Page 9
Image Swapping
One of the most commonly used features of JavaScript is the ability to change images on a mouseover. Unfortunately, Microsoft Internet Explorer 3.0 does not support image replacement. So if you're using IE 3.0, it might be time to upgrade to IE 4.0 or switch to Netscape.
Here's a quick and dirty example of a basic image swap.
Let's go through the example step by step. The first line of interest is:
<img src="button_r.gif" name="the_image">
This is just like a standard <img src= > tag except this one has been given a name: the_image. This name could be anything: my_image, a_box, whatever but it can't have any spaces in it.
The next line of interest is:
<a href="#"
onMouseOver="document.the_image.src='button_d.gif';">
change</a>
This is where the image swap happens. It's just like the onMouseOver you saw before. The active piece of JavaScript, which appears in the quotes of the onMouseOver is this:
document.the_image.src='button_d.gif';
This statement says, "find the image called 'the_image' and change its src to button_d.gif." Note that there are double quotes around the whole statement, and 'button_d.gif' takes single quotes. Although quotes are interchangable, if you have one set of quotes inside another set of quotes, the sets have to be of different kinds. So you could either do " 'something' " or ' "something" ' but not " 'something" ' or " "something" ". Got it?
Just as there was a lot of detail in what makes document.writeln() work, I'm not telling you exactly how this image swap is working. You'll learn the details of both when we look at object-oriented programming and the Document Object Model in the next lesson.
An important caveat about image swapping is that the image you're switching to should be the same size as the original. If it's not, it'll get smashed or stretched to fit the original's size.
For now, you're ready for today's homework.
next page»
|