Java Reference
In-Depth Information
Save this as ch6_examp3.htm. You will also need four image fi les, called usa.gif, canada.gif,
jamaica.gif, and mexico.gif. You can create these images yourself or obtain the ones provided with
the code download for the topic.
A prompt box asks you to enter a number from 0 to 3 when this page loads into the browser. A different
image will be displayed depending on the number you enter.
At the top of the page you have your HTML <img/> element. Notice that the src attribute is left empty
and is given the name value img1.
<img name=”img1” src=”” border=”0” width=”200” height=”150”>
Next you come to the script block where the image to be displayed is decided. On the fi rst line, you defi ne
an array containing a list of image sources. In this example, the images are in the same directory as the
HTML fi le, so a path is not specifi ed. If yours are not, make sure you enter the full path (for example,
C:\myImages\mexico.gif ).
Then you ask the user for a number from 0 to 3, which will be used as the array index to access the
image source in the myImages array.
var imgIndex = prompt(“Enter a number from 0 to 3”,””);
Finally, you set the src property of the img object to the source text inside the myImages array element
with the index number provided by the user.
document.images[“img1”].src = myImages[imgIndex];
Don't forget that when you write document.images[“img1”], you are accessing the img object stored
in the images collection. You've used the image's name, as defi ned in the name attribute of the <img/>
element, but you could have used document.images[0]. It's an index position of 0, because it's the fi rst
(and only) image on this page.
The links Collection
For each hyperlink element <a/> defi ned with an href attribute, the browser creates an a object. The most
important property of the a object is the href property, corresponding to the href attribute of the tag. Using
this, you can fi nd out where the link points to, and you can change this even after the page has loaded.
The collection of all a objects in a page is contained within the links collection, much as the img
objects are contained in the images collection, as you saw earlier.
Responding to the User's Actions with Events
There's no doubt that JavaScript is a useful tool in web programming. As you've seen thus far, it's capa-
ble of limited data processing. In most web applications, however, data processing is typically relegated
to the server, as it is better suited for that task. The user uses the web application through the browser,
and as such, the browser is responsive to the user's actions. Wouldn't it be great if you could execute
code for a specifi c user action? Well, you can with events.
Search WWH ::




Custom Search