Writing HTML | About | FAQ | Alumni | Kudos | References | Tags | Lessons | previous | next |

27d. JavaScript : Swapping Images

Dynamic Animation!

Move Your Mouse over the Bottle!

Move it Away!

Are You Ready to Create the Same Effect?


After this lesson you will be able to:

Write the JavaScript code to implement image swapping.


Note: If you do not have the working documents from the previous lessons, download a copy now.

In this lesson we show you how to create an effect that you likely have seen at other web sites-- causing an inline image to change when you move the mouse over it or click on it. For the example below, the arrow will "bulge" when the mouse moves over it, and it will change to a "pushed-down" appearance, once it is clicked:

left arrow button

Once the button is "locked" down, you must Reload this page in your browser to reset it.

The most common use of this technique is to animate hyperlinked images that act as buttons, so the viewer gets an extra reinforcement that the object under the mouse is something worth clicking.

While you are free to use what you learn in this lesson to make buttons pop and jump, our stodgy opinion is that this adds nothing to the information on the page, so our example will show you a use that we think is a bit more worth the effort.

You should consider another factor; for every image that you will cause to change when the mouse moves over it, you actually must download 2 different images, and as you will see shortly, this must be done before the HTML for the page loads. Therefore, this can increase the precious wait time that the viewer will be watching a blank screen.

The way image mouseOver swapping works goes something like:

  1. Web browser starts reading the HTML for the page
  2. The <HEAD>...</HEAD> area includes statements that first download two image files and place them into temporary hidden storage.
  3. The normal <img...> tag loads the image that should first appear.
  4. A JavaScript "event handler" in a hyperlink tag around the image tests for whether the mouse is leaving or entering the area of the page covered by the image.
  5. If the mouse enters the image, we call a JavaScript function to swap the file source for the image for the file that represents the appearance for when the mouse is over the image.
  6. When the mouse leaves the area of the image, we call a second JavaScript function to swap back the original image.
NOTE: To work correctly, the images that are swapped for each other must be the same width and height.

Below is a generic method for button swapping. The one used in this page has a few more features that you are encouraged to explore by looking at the HTML source of this lesson page.

JavaScript Image Swapping
HTML codeexplanation

<html> <head> <title>My Page</title> <head> <SCRIPT LANGUAGE="JavaScript"> <!--

Typical top of standard HTML file that has JavaScript functions in its <HEAD>...</HEAD>.
if (document.images) {
This is a test that determines if the web browser understands the image storage functions needed for swapping images. If this test is false, we would skip the rest of the code and just display a static image.
  var button1_up = new Image();
  button1_up.src = 'button_up.gif";
We create a variable that is the type that represents Images. The second line assigns the src property with the path to the first image file to the "up" version of the image.
  var button1_over = new Image();
  button1_over.src = 'button_over.gif";
We create a second Image variable that assigns the src property to the path to the second image file for the "up" version of the image.
function over_button() {
  if (document.images) {
    document["buttonOne"].src = button1_over.src
This function, when called will again make sure the browser can do the image swapping. If so, it looks inside its internal list of inline images stored in the document object, and assigns it the variable that represents the image for the mouse over or highlighted image.
function up_button() {
  if (document.images) {
    document["buttonOne"].src = button1_up.src
This function works almost the same, except that it will make the image swap back to the "up" version.
End of the JavaScript and continuation of the HTML to display the page's content.

<A HREF="file.html"
  <img src="button_up.gif" alt="click me"
    width="XX" height="YY" name="buttonOne"
The tag used to load the first view of the image (the "up" version). Notice that we have assigned the image inside the <img...> tag a unique name, "buttonOne", that we can refer to it using code like document["button name"] The hyperlink tag contains a JavaScript event handler, onMouseOver that will trigger a call to our function to swap in the "highlight" image when the mouse moves over the image. Likewise, the onMouseOut event will call our other function to change the image back when the mouse leaves, or "moves out" of the image area.

Now we will see how this works in our volcano web example. Rather than just animating buttons, we are going to simulate a microscope!

As part of our Introduction, we will add a new section that describes volcanic rocks, and include an image of one kind, called "pumice". We will use JavaScript to change the image to a second one that shows a cut away view of how pumice looks under a microscope. By moving the mouse on and off the image, we can compare the two different views (Okay, we admit it is not much more creative than animating buttons and one could achieve the same result by placing the images side by side...)

  1. Go to the Lesson 27d Image Studio to get the two image files needed for this lesson. The should be placed in the pictures directory with all of your other image files.
  2. Open the intro.html file in your text editor.
  3. Inside the <HEAD>...</HEAD> tags, add the following JavaScript code:
    <SCRIPT LANGUAGE="JavaScript">
    if (document.images) {
       var pum1 = new Image();
       pum1.src = "../pictures/pumice.gif";
       var pum2 = new Image();
       pum2.src = "../pictures/pumice2.gif";
    function show_rock() {
    	if (document.images) {
    		document["pum"].src = pum2.src;
    function hide_rock() {
    	if (document.images) {
    		document["pum"].src = pum1.src;
    NOTE: We have created two JavaScript "holder" variables that represent the two images. We will call the show_rock() function to swap in the microscope view image pumice2.gif and the hide_rock() function to swap back the original image. These events occur for an image named "pum" we will next identify in the HTML code.
  4. After the end of our table on well known volcano eruptions, following the sentence that ends:
      than ones observed by humans.
    We will add a new section about Volcanic Rocks. It will contain the image for the pumice rock and the code for the JavaScript image swapping:
    <h3 align=center>Volcanic Rocks</h2>
    Scientists study rocks at many different scales.<p>
    <b>Pumice</b> is one kind of rock formed by volcanic eruptions
    <A HREF="intro.html"
      onClick="alert('Move the mouse over the rock to see a magnified view.');
      return false"
      onMouseOver="show_rock(); window.status='description of explosiveness scale';
      return true"
    <IMG SRC="../pictures/pumice.gif" align=right ALT="picture of pumice"
      WIDTH="220" HEIGHT="170" hspace=12 vspace=12 name="pum" border=0></A>
    that are very explosive. Hot, frothy volcanic <b>magma</b> quickly cools,
    leaving a structure of many twisted air holes inside. Pumice is thus very
    light weight.
    If you move your mouse over the image, you can see how pumice looks
    under the microscope.
    A <b>thin section</b> is a layer of the rock cut so thin that the
    light from a microscope shines through, allowing us to see the
    structure of the rock.
    The twisted chambers here represent the air pockets preserved inside
    the rock when this rock blew out of a volcano.
    <br clear=right>
    NOTE: Take extra care on the code for the <img...> tag; it is pretty complex now! It now handles the mouseOver actions, displays a status bar message (like we did in lesson 27a), and will display an alert message in case the viewer clicks the image (keeping them on the same page). The image is also right aligned and has extra padding around it using (hspace and vspace)
  5. Save and Reload

Check Your Work

Compare your web pages with this sample of how it should appear. If your pages are different from the sample or the hypertext links do not work correctly, review the text you entered in the text editor. Note that JavaScript is very sensitive to typographical mistakes -- one missing quote or semi-colon can ruin the page! Make sure to check that you do not have extra RETURN characters inside your JavaScript statements.


Review topics for this lesson:

  1. What areas of your HTML document must be edited to create JavaScript image swapping?
  2. What is the difference between onMouseOver and onMouseOut?
  3. What does the viewer see if their browser returns a value of FALSE for the expression document.images?
  4. What are the essential ingredients to write JavaScript code for image swapping (hint: consider the image files, code to load images, code to swap images, and code to initiate events)?

Independent Practice

Find some images that you can use for swapping; remember they must be the same exact size! Use our code to create the same effect in your own pages. What would it take to have two different images be able to change like this? Why would this approach be less desirable if our page had 10 active images that could be swapped for alternative ones?

Note that you can also write JavaScript functions to perform a different task generated by a mouse click:

<a href="file.html" onMouseOver="over_button()" onMouseOut="up_button()"
  <img src="button_up.gif" alt="click me" width="XX" height="YY"
  name="buttonOne" border=0>

provided that you had written a JavaScript function in your <HEAD>...</HEAD> to react to this event

Coming Next....

It's time we livened things up with some interactive FORMs...

GO TO.... | Lesson Index | previous: "JavaScript: Window Openers" | next: "FORMs"

Writing HTML: Lesson 27d: A Wee Dose of JavaScript : Swapping Images
©1994-1999 Maricopa Center for Learning and Instruction (MCLI)
Maricopa Community Colleges

The 'net connection at MCLI is Alan Levine
Comments to alan.levine@domail.maricopa.edu

URL: http://www.mcli.dist.maricopa.edu/tut/tut27d.html