Watch our 3-minute video to find out how you can learn JavaScript with a live instructor.
Additional Resources

Working with Images

In this lesson of the JavaScript tutorial, you will learn...
  1. To create image rollovers.
  2. To create backward-compatible image rollovers.
  3. To preload images.
  4. To create a slide show.

Image Rollovers

Image rollovers are commonly used to create a more interesting user experience and to help highlight navigation points. When the user hovers the mouse over an image, the source of the image is modified, so that a different image appears. When the user hovers the mouse back off the image, the original source is restored. The code below shows how to create a simple rollover.

Code Sample: DynamicImages/Demos/SimpleRollover.html

<html>
<head>
<title>Simple Image Rollover</title>
</head>
<body>
<div style="text-align:center;">
<h1>Simple Image Rollover</h1>
<img name="MyImage" src="Images/Banner.jpg" border="0"
 onmouseover="this.src = 'Images/Hulk.jpg';"
 onmouseout="this.src = 'Images/Banner.jpg';">
<p>Who are you calling simple?</p>
</div>
</body>
</html>
Code Explanation

The mouse-over event is captured with the img tag's onmouseover event handler. When this happens, the following JavaScript code is called.

this.src = 'Images/Hulk.jpg';

The this object refers to the current object - whatever object (or element) the this keyword appears in. In the case above, the this object refers to the img object, which has a property called src that holds the path to the image. The code above sets the src to "Images/Hulk.jpg".

Likewise, the mouse-out event is captured with the img tag's onmouseout event handler. When this happens, the following JavaScript code is called.

this.src = 'Images/Banner.jpg';

This code sets the src to "Images/Banner.jpg," which is what it originally was.

Backward Compatibility

The code above should work fine in Firefox, Internet Explorer 4.0 and later, and Netscape 6 and later. However, in earlier versions of browsers, images could not capture mouse events. The workaround is to wrap the <img> tag in an <a> tag and to put the event handlers in the <a> tag as shown below.

Code Sample: DynamicImages/Demos/SimpleRollover-backward.html

<html>
<head>
<title>Simple Image Rollover</title>
</head>
<body>
<div style="text-align:center;">
<h1>Simple Image Rollover</h1>
<a href="#" 
 onmouseover="document.MyImage.src = 'Images/Hulk.jpg';"
 onmouseout="document.MyImage.src = 'Images/Banner.jpg';">
<img name="MyImage" src="Images/Banner.jpg" border="0"></a>
<p>Who are you calling simple?</p>
</div>
</body>
</html>

An Image Rollover Function

Image rollovers can be handled by a function as well. The two examples below show an image rollover function for modern browsers and a backward-compatible image rollover function.

Code Sample: DynamicImages/Demos/SimpleRolloverFunction.html

<html>
<head>
<title>Simple Image Rollover Function</title>
<script type="text/javascript">
function imageRollover(img, imgSrc){
 img.src = imgSrc;
}
</script>
</head>
<body>
<div style="text-align:center;">
<h1>Simple Image Rollover Function</h1>
<img name="Banner" src="Images/Banner.jpg" border="0" 
 onmouseover="imageRollover(this, 'Images/Hulk.jpg');"
 onmouseout="imageRollover(this, 'Images/Banner.jpg');">
<img name="Bruce" src="Images/Bruce.jpg" border="0" 
 onmouseover="imageRollover(this, 'Images/Batman.jpg');"
 onmouseout="imageRollover(this, 'Images/Bruce.jpg');">
<p>Who are you calling simple?</p>
</div>
</body>
</html>

Code Sample: DynamicImages/Demos/SimpleRolloverFunction-backward.html

<html>
<head>
<title>Simple Image Rollover Function</title>
<script type="text/javascript">
function imageRollover(imgName, imgSrc){
 if (document.images) {
  document.images[imgName].src = imgSrc;
 }
}
</script>
</head>
<body>
<div style="text-align:center;">
<h1>Simple Image Rollover Function</h1>
<a href="#" 
 onmouseover="imageRollover('MyImage', 'Images/Hulk.jpg');"
 onmouseout="imageRollover('MyImage', 'Images/Banner.jpg');">
<img name="MyImage" src="Images/Banner.jpg" border="0"></a>
<p>Who are you calling simple?</p>
</div>
</body>
</html>
Code Explanation

Why the check for document.images? Some early versions of browsers don't support the images array.

Preloading Images

When working with files on a local machine, image rollovers like the ones we have seen in previous examples work just fine. However, when the user first hovers over an image rollover image, the new image file has to be found and delivered to the page. If the new image is on a far-away server, this can take a few moments, causing an ugly pause in the rollover effect. This can be prevented by preloading images.

Images can be preloaded by creating an Image object with JavaScript and assigning a value to the src of that Image. A sample is shown below.

Code Sample: DynamicImages/Demos/PreloadingImages.html

<html>
<head>
<title>Preloading Images</title>
<script type="text/javascript">

var IMAGE_PATHS = [];
IMAGE_PATHS[0] = "Images/Hulk.jpg";
IMAGE_PATHS[1] = "Images/Batman.jpg";

var IMAGE_CACHE = [];

for (var i=0; i<IMAGE_PATHS.length; i++) {
 IMAGE_CACHE[i] = new Image();
 IMAGE_CACHE[i].src = IMAGE_PATHS[i];
}

function imageRollover(img, imgSrc) {
 img.src = imgSrc;
}
</script>
</head>
<body>
<div style="text-align:center;">
<h1>Simple Image Rollover Function</h1>
<img name="Banner" src="Images/Banner.jpg" border="0" 
 onmouseover="imageRollover(this, 'Images/Hulk.jpg');"
 onmouseout="imageRollover(this, 'Images/Banner.jpg');">
<img name="Bruce" src="Images/Bruce.jpg" border="0" 
 onmouseover="imageRollover(this, 'Images/Batman.jpg');"
 onmouseout="imageRollover(this, 'Images/Bruce.jpg');">
<p>Who are you calling simple?</p>
</div>
</body>
</html>
Code Explanation

Notice that the code is not in a function. It starts working immediately as follows:

  1. An array called IMAGE_PATHS is created to hold the paths to the images that need to be preloaded.
    var IMAGE_PATHS = [];
  2. An array element is added for each image to be be preloaded.
    IMAGE_PATHS[0] = "Images/Hulk.jpg";
    IMAGE_PATHS[1] = "Images/Batman.jpg";
  3. An array called IMAGE_CACHE is created to hold the Image objects that will hold the preloaded images.
    var IMAGE_CACHE = [];
  4. A for loop is used to create an Image object and load in an image for each image path in IMAGE_PATHS.
    for (var i=0; i<IMAGE_PATHS.length; i++) {
     IMAGE_CACHE[i]=new Image();
     IMAGE_CACHE[i].src=IMAGE_PATHS[i];
    }

Exercise: Creating a Slide Show

Duration: 20 to 30 minutes.

In this exercise, you will practice working with images by creating a slide show.

  1. Open DynamicImages/Exercises/SlideShow.html for editing.
  2. Write code to preload Images/Banner.jpg, Images/Hulk.jpg, Images/Bruce.jpg, and Images/Batman.jpg. The paths to the images should be stored in an array called IMAGE_PATHS. The Image objects should be stored in an array called IMAGE_CACHE.
  3. Create a function called changeSlide() that takes one parameter: dir, and behaves as follows:
    • If dir equals 1, it changes the slide to the next image as stored in the IMAGE_PATHS array.
    • If dir equals -1, it changes the slide to the previous image as stored in the IMAGE_PATHS array.
    • If the user is viewing the last slide and clicks the Next button, the first slide should appear.
    • If the user is viewing the first slide and clicks the Previous button, the last slide should appear.
  4. Test your solution in a browser.
  1. Add a dropdown menu below the Previous and Next buttons that contains the names of the images without their extensions: "Banner", "Hulk", "Bruce" and "Batman".
  2. When the user selects an image from the dropdown, have that image appear above.
  3. When the user changes the image above using the Previous and Next buttons, have the dropdown menu keep in sync (i.e, show the name of the current image).

The solution should look like the screenshot below.

Working with Images Conclusion

In this lesson of the JavaScript tutorial, you have learned how JavaScript can be used to manipulate HTML images to create image rollover effects and slide shows.

To continue to learn JavaScript go to the top of this page and click on the next lesson in this JavaScript Tutorial's Table of Contents.

Use of http://www.learn-javascript-tutorial.com (Website) implies agreement to the following:

Copyright Information

All pages and graphics on Website are the property of Webucator, Inc. unless otherwise specified.

None of the content on Website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of pages or content on Website

This content may not be printed or saved. It is for online use only.


Linking to Website

You may link to any of the pages on Website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

Website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).


For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm