Java Reference
In-Depth Information
Next you come to the script block where the image to be displayed is decided. On the first line, you
define an array containing a list of image sources. In this example, the images are in the same directory
as the HTML file, so a path is not specified. 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[0].src = myImages[imgIndex];
Don't forget that when you write
document.images[0]
, you are accessing the
img
object stored in the
images
collection. It's an index position of
0
, because it's the first (and only) image on this page.
the links Collection
For each hyperlink element
<a/>
defined 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 find 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.
determining the user's BroWser
Many browsers, versions of those browsers, and operating systems are out there on the Internet,
each with its own version of the BOM, its own set of features, and its own particular quirks. It's
therefore important that you make sure your pages will work correctly on all browsers, or at least
degrade gracefully
, such as by displaying a message suggesting that the user upgrade his or her
browser.
You have two ways to test if the browser can execute your code:
feature detection
and
browser
sniffing.
. They share a similar end goal (to execute code for a given browser), but they are used for
different purposes.
feature detection
Not all browsers support the same features (although today's modern browsers do a very good job
of it). When we say “feature,” we're not referring to tabbed browsing, download managers, and so
on. We mean features that we, as JavaScript developers, can access and use in our code.