javascript tutorials

Image Mouseover

Ouch!
Mouse over this image.
Everyone's favorite JavaScript trick is to swap images. Images can be changed by the actions of the web user, usually by moving the mouse over the image or by clicking something. The creates the illusion of movement or animation.
Like this image

How is this done? This tutorial shows you how to create a rollover image with JavaScript.

Simple Rollover Image -

  • You will need 2 images. An image, which we will name 'eye', will be the target of the rollover. One image appears by default and the second will appear only when the user places the mouse over the image. A mouseout function will again replace the 'eye' image with the defaut open eye image.
  • Insert the following script into your head tag area
  • <script type="text/javascript">
    if (document.images)
    {
    img1 = new Image();
    img2 = new Image();

    img1.src = "eye-open.gif";
    img2.src = "eye-closed.gif"

    }

    else
    {
    img1 = ""
    img2 = ""
    document.eye = ""
    }
    </script>

  • The image is entered in your web page as shown below:
    <a href="javascript:void(0);" onmouseover="document.eye.src=img2.src" onmouseout="document.eye.src=img1.src">
    <img name="eye" src="eye-open.gif"></a>
  • The image is given an id, in this case we will call it 'eye'.
  • Wrap the image with a blank a tag (href="javascript:void(0);")
  • A mouseover and mouseout function are added to the blank 'a' tag.
  • The onmouseover tag function chages the source of 'eye' on the document to img2 (which is defined as 'eye-closed.gif' in the header script.)
  • The onmouseout tag function chages the source of 'eye' on the document back to img1 (which is defined as 'eye-open.gif' in the header script.)

And there you have it! You have an easy rollover image script that is easy to understand.

Custom Search
Tutorials JavaScript Resouces
Some developers offer ready made
scripts that can be modified to work
in your website. Some of these
scripts are free and some require a
small fee, but they are well worth it: