11.3 Introduction to Images


A picture is worth a thousand words. Whether it's a slide show, banner, movie, or photo album, the Web contains a huge collection of images. Any time you buy something online, there is usually an image associated with the item, maybe a small image, and then a bigger image if you want more detail. Whatever it is, a book, a house, a pair of shoes, or a toy, we like to see it before we put it in our virtual shopping cart and pay the money.

Images can be links, clickable image maps, banners, marquees, billboards, or rollovers ”you name it. With HTML, the images you load are static, and just sit on the page. They cannot be changed without loading a brand-new page, and loading a lot of images takes time. JavaScript brings a new dimension to working with images. Instead of viewing a static image on the page, now you can create rollovers, slide shows, cycling banners, and more. You can create dynamic images that can be changed on the fly, adding animation and drama to your Web page. Before getting into the fun of images, we will look at how JavaScript views the image. In Chapter 12, "Handling Events," and Chapter 15, "Dynamic HTML: Style Sheets, the DOM, and JavaScript," you utilize what you learn here to see the full potential of image creation with JavaScript.

11.3.1 HTML Review of Images

Before using images with JavaScript, the following section reviews the basics of using images in a static Web page.

Table 11.21. HTML image tags.

Tag

Attributes

Description

IMG

 

Starting tag for loading an image.

 

ALIGN

Floats the image either to the left or right side of the page, or aligns the image with text in directions, texttop, top, middle, absmiddle, bottom , or absbottom .

 

ALT

Alternative text in case the image doesn't appear.

 

BORDER

The width in pixels of an image border.

 

HEIGHT

Height of the image in pixels.

 

HSPACE

Adds space, in pixels, to both the right and left sides of the image.

 

SRC

Contains the URL, location of the image relative to the document root of the Web page.

 

VSPACE

Adds space, in pixels, to both the top and bottom of the image.

 

WIDTH

Width of the image in pixels.

MAP

 

Starting tag for an image map. Image maps link areas of an image with a set of URLs. Clicking on an area of the map sends the user to that page.

 

ID

The name of the image map.

 

NAME

Also the name of the image map.

AREA

 

Defines the clickable areas of the image map.

 

ALT

Describes what happens when the user clicks.

 

COORDS

Determines the shape of a rectangle, circle, or polygon in x,y pixel coordinates.

 

HREF

The address of the page that will appear when the user clicks in a particular area.

 

SHAPE

Assigned a type , where type represents the shape of the area.

Using an Image in an HTML Web Page

The following example is an HTML file linked to an image. In this example, we review the way inline images are created in a document.

Example 11.32
 <html>     <head><title>HTML Images</title></head>     <body bgcolor="lightblue">     <h2>&nbsp;&nbsp;This Is Baby William</h2> 1  <img src="baby.jpg" alt="baby" border=2 align="left" hspace="10"  2  width="220" height="250">  3   <pre>     Father calls me William,           sister calls me Will,     Mother calls me Willie,         but the fellers call me Bill!     Mighty glad I ain't a girl--         ruther be a boy,     Without them sashes, curls, an' things         that's worn by Fauntleroy!     Love to chawnk green apples         an' go swimmin' in the lake--     Hate to take the castor-ile         they give for belly-ache!     Most all the time, the whole year round,         there ain't no flies on me,     But jest 'fore Christmas         I'm as good as I kin be!     </pre></body>     </html> 

Eugene Field, Jest 'Fore Christmas , in Childcraft , Vol. 2, (Chicago: Field Enterprises, Inc., 1949).

EXPLANATION

  1. The image src attribute defines where the image is located. This image, baby.jpg , is located where the HTML file called image.html is found, normally under the document root of your browser. If the image can't be loaded, the alt attribute specifies text that will appear in its place. The image will be aligned at the left-hand side of the page and will have a thin black border around it. There will be 10 pixels of space on both the left- and right-hand sides of the image. This keeps the text from jamming up too close to the picture.

  2. The width and height attributes of the img tag allow you to specify the size of your image in pixels. If you right-click on an image (Windows), a pop-up window will appear where you can select Properties to obtain info about your image.

  3. This is a <pre> tag that is followed by all the text that appears at the right-hand side of the image. See Figure 11.48.

    Figure 11.48. Using images in an HTML page. Output from Example 11.32.

    graphics/11fig48.jpg

11.3.2 JavaScript and the image Object

The image object is a property of the document object and gives you access to the images that have been loaded into a document. It corresponds to the HTML <img> tag. As each HTML form is a JavaScript element of the forms[] array, each image is assigned to the images[] array [3] in the order in which the image appears within the document. The first image would be represented as document.image[0] , the next as document.image[1] , and so on. As with forms, images can also be named. The properties for the image object correspond to the HTML attributes of the <img> tag, such as width, height, border, vspace, and hspace , are shown in Table 11.22. [4] As of Netscape 6 and Internet Explorer 4, it is possible to assign values to these properties to dynamically change the size, shape, and border of the image. There are no common methods for the image object.

[3] Implemented starting in JavaScript 1.1.

[4] These properties are common to both Netscape and Internet Explorer. IE, however, supports many more than those listed here.

JavaScript also provides the image object with event handlers that are triggered when the image is loaded, a mouse crosses the image, or the image is replaced when the user clicks on a link. The event handlers are discussed in Chapter 12, "Handling Events."

For preloading offscreen images, JavaScript provides an image constructor. The constructor is used if you have large images that will take time to download or images that are being replaced dynamically within the page. The images are preloaded into memory (but not displayed) and available from the cache when the user requests them, thus making the response time much faster.

Table 11.22. image object properties.

Property

HTML <IMG> Attribute

Description

border

border

An integer value determining the width of an image border in pixels

complete

 

A Boolean value returning true if Navigator has finished downloading the image

height

height

An integer representing the height of the image in pixels

hspace

hspace

An integer representing the horizontal space (pixels) around the image

lowsrc

lowsrc

Specifies an optional image to display for a low-resolution device

name

name

A string containing the name of the image

prototype

 

Used to add user-specified properties to an image object

src

src

A string containing the path and name of the image

vspace

vspace

An integer representing the vertical space (pixels) around the image

width

width

An integer representing the width of the image in pixels

Replacing Images Dynamically with the src Property

By changing the src property of an image, it is possible to dynamically replace one image with another. You can create an array of images with the Array() constructor, and dynamically assign any one of these images to the src property of the JavaScript images[] array.

Example 11.33
 <html>     <head><title>HTML Images</title>     <script language="JavaScript"> 1  var myImages=new Array("baby1.jpg", "baby2.jpg", "baby3.jpg",   "baby4.jpg");  2       index_val=0; 3  function next_image(){  4           index_val++; 5           if (index_val < myImages.length){ 6  document.images["display"].src = myImages[index_val];  //  could say document.display.src or  //  document.images[0].src  } 7           else{                index_val=0;  document.images["display"].src = myImages[index_val];  }         } 8  function previous_image(){  index_val--; 9           if (index_val >= 0){                document.images["display"].src = myImages[index_val];             } 10          else{                index_val=myImages.length - 1;                document.images["display"].src = myImages[index_val];             }         }     </script>     </head>     <body bgcolor="cornflowerblue">     <h2>&nbsp;&nbsp;Baby Gallery</h2> 11  <img name="display" src="baby.jpg" width="220" height="250" >  <br> 12  <a href="javascript:next_image()">  Go to next baby<br>     </a> 13  <a href="javascript:previous_image()">  Go to previous baby<br>     </a>     </body>     </html> 

EXPLANATION

  1. The array myImages consisting of four images is created by the Array() constructor.

  2. The index value for the array is assigned to a variable called index_val .

  3. A function called next_image() is defined. When called, the function will cause the next image in the array to be displayed.

  4. By increasing the value of the index, the next image in the array will be accessed.

  5. As long as the end of the array hasn't been reached, the block will be entered and the new image displayed.

  6. The name of the image, display , is used as an index into the images[] array to reference the default image by name. By assigning a new image (from the myImages array) to the images src property, the current image will be replaced by the new image.

  7. If the end of the array has been reached, the statements within the else block will be executed, resetting the array index back to the beginning, index 0.

  8. A function called previous_image() is defined. When called, it will go backward in the array and cause the previous image to be displayed.

  9. If the index value is still 0, we are still within the boundaries of the array.

  10. If by subtracting one from the index value, we have ended up with a value of “1, we are out of the bounds of the array, and will set the index value back to the size of the array, its length “1.

  11. This is the initial image displayed on the screen before the user initiates an action.

  12. When this link is clicked, the JavaScript function called next_image() is invoked.

  13. When this link is clicked, the JavaScript function called previous_image() is invoked. See Figure 11.49.

    Figure 11.49. Output from Example 11.33.

    graphics/11fig49.jpg

Example 11.34
 <html>     <head><title>HTML Replacing Images</title></head>     <body bgcolor="cornflowerblue">     <h2>&nbsp;&nbsp;This Is Baby William</h2> 1  <img name="display" src="baby.jpg" width="220" height="250" >  <script language="JavaScript"> 2  var myImages=new Array("baby1.jpg", "baby2.jpg", "baby3.jpg");  3       var n = prompt("Pick a number between 1 and 3",""); 4       n--; 5  document.images["display"].src = myImages[n];  //  document.images[0].src = myImages[n]  </script></body>     </html> 

EXPLANATION

  1. An HTML inline image called display is created. Its source is a file called baby.jpg with the width and height defined in pixels.

  2. An array object called myImages is created with the Array() constructor. The elements of the array are three .jpg files.

  3. The user is prompted to pick and number between 1 and 3, which will determine which image will be displayed. The user input is assigned to variable n .

  4. Array indices start at 0. The user entered a number between 1 and 3, and since n will be used as an index into the array, it must be decremented to produce an index number ranging from 0 to 2.

  5. The images array can be indexed by number or name. In this example, display is the name given to the default image shown on the screen, baby.jpg . By changing the src property, the default image will be replaced by any one of the images listed in the myImages array. See Figure 11.50.

    Figure 11.50. Output from Example 11.34 (left) after the user picks a number (right).

    graphics/11fig50.jpg

Preloading Images and the Image() Constructor

If you assign a new image to the src property of an image object, there may be some lag in the time it takes to download the image from the server. And if you have a slow connection, this can be a real turnoff, to the point that you don't even bother to wait for the image to load. To solve this problem, the Image() constructor allows you to preload an offline image; this puts the image in the browser's cache before it is used. This technique of caching the image makes the response time much faster, especially when you have large images, animation, rollovers, and the like. The Image() constructor can also define the size (height and width, in pixels) of the cached image. For seamless transition when replacing one image with another, both images should be of the same size. To use the Image() constructor, see below.

FORMAT

 
 var newImage = new Image(); var newImage = new Image(height, width) newImage.src="image.gif"; 

Example:

 
 var myImage = new Image(200,300); myImage.src="baby.gif"; 
A Simple Rollover with a Mouse Event

We talked about event handlers with the form object and now we will demonstate the use of an event handler with the image object. For a complete discussion, see Chapter 12, "Handling Events." The objective of the next example is to change the image when the mouse rolls over a link, and to change it back when the mouse moves away from the link. There are two images involved: the image that initially appears on the page and the image that replaces it when the mouse rolls over the link associated with it. Both of the images are preloaded with the Image() constructor. The JavaScript onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event is triggered when the mouse moves away from the link.

Example 11.35
 <html>     <head><title>Preloading Images</title></head>     <h2>&nbsp;&nbsp;This Is Baby William</h2>     <script language="JavaScript"> 1       if(document.images){ 2  var baby1=new Image();  //  Preload an image  3  baby1.src="baby1image.jpg";  }         if (document.images){ 4  var baby2=new Image();  //  Preload an image  5  baby2.src="baby2image.jpg"  ;         }     </script>     <body bgcolor="cornflowerblue"> 6   <a href="#"  onMouseOver="document.willy.src=baby2.src;"  7  onMouseOut="document.willy.src=baby1.src;"  > 8  <img name="willy"   src="baby1image.jpg"   align="left"  alt="baby" border=2  hspace="10"         width="220" height="250">     </body>     </html> 

EXPLANATION

  1. Dynamic images are not available on browsers older than Navigator 3 and IE 4. The if statement checks for the existance of the image object. If the image object is unavailable, this block will not be executed.

  2. The Image() constructor creates and preloads a new image object called baby1 .

  3. The src property is assigned the name of the external image file called baby1image.jpg .

  4. The Image() constructor creates and preloads a new image object called baby2 .

  5. The src property is assigned the name of the external image file called baby2image.jpg .

  6. The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. The link is an image. The onMouseOver event handler is triggered when the user's mouse moves onto the link, and the onMouseOut event handler is triggered when the user's mouse moves away from the link (image). When the mouse moves over the image, the baby image changes from the first image to the second one. When the mouse is moved away from the image, the original image is displayed. Going down the JavaScript hierarchy, we start with the document , then to willy ( images[0] or images["willy"] ), then to the src property that is assigned the image object. One image is replaced with another.

  7. When the mouse is moved away from the link, the intial image baby1image.jpg will reappear on the screen.

  8. The initial external image called baby1image.jpg is named willy and is aligned on the left-hand side of the screen. The output is shown in Figure 11.51.

    Figure 11.51. Before the mouse rolls over the image (left), as the mouse hovers over the image (middle), and when the mouse moves away from the image (right).

    graphics/11fig51.jpg

Randomly Displaying Images and the onClick Event

By using the Math object's random() method, it is sometimes fun to randomly generate pictures from a list of images. Example 11.36 demonstrates how to change the src attribute of an image object by using a random number as the index of an elment in an image array. All of the images are preloaded by using the Image() constructor, greatly improving on the time it takes to load the images.

Example 11.36
 <html>     <head><title>Preloading Images</title></head>     <script language="JavaScript"> 1       ImageHome=new Array(3); 2       for(var i=0; i<3; i++){  ImageHome[i]=new Image();  } 3       ImageHome[0].src="baby1.jpg";         ImageHome[1].src="baby2.jpg";         ImageHome[2].src="baby3.jpg"; 4  function myRandom(){  5           var n=ImageHome.length - 1; 6           var randnum=Math.floor(Math.random() * (n + 1)); 7  document.images["display"].src = ImageHome[randnum].src;  }     </script>     </head>     <body bgcolor="cornflowerblue"><center>     <h2>&nbsp;&nbsp;This Is Baby William</h2> 8  <img name="display"   src="baby.jpg"   border=5   width="200" height="250" >  <p>     <form> 9   <input type="button"         value="Click Here for Baby Picture" 10  onClick="myRandom()"  >         </form>         </center>         </body>         </html> 

EXPLANATION

  1. The Array() constructor creates an array object to consist of three elements. This array will be used to hold three images.

  2. The Image() constructor will preload and cache three images and assign them to the array created in line 1.

  3. The src property of the first element of the image array is assigned an image called baby1.jpg . Each array element is assigned a different image.

  4. The function called myRandom() is defined. It produces a random number that will be used as the index into the image array, causing a random picture to be displayed on the screen.

  5. The variable called n is assigned the value of the length of the image array minus 1.

  6. The variable called randnum is assigned a random whole number between 1 and 3, the value returned from the Math object's random method.

  7. Instead of using a number to access the image array, a string is used. The string is the name given to the HTML image defined on line 8. This is the image that initially appears in the browser window. In the JavaScript tree, this image is represented as document.images[0].src or document.display.src or d ocument.images["display"].src . Either way, this image will be replaced with the value of the image in the array ImageHome[randnum].src.

  8. The inline image, called baby.jpg is displayed on the screen when the program starts. It is named display .

  9. This form input type creates a button on the screen.

  10. When the user clicks the button, the onClick event is fired up, and the event is handled by calling myRandom() , which displays a random image. See Figure 11.52.

    Figure 11.52. Each time the user clicks the button, a random picture is displayed.

    graphics/11fig52.jpg



JavaScript by Example
JavaScript by Example (2nd Edition)
ISBN: 0137054890
EAN: 2147483647
Year: 2003
Pages: 150
Authors: Ellie Quigley

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net