Java Reference
In-Depth Information
keep looping until you get a new image, at which point myImages[newImgNumber] will not be found
in the existing src and -1 will be returned by the indexOf() method, breaking out of the loop.
while (imgClicked.src.indexOf(myImages[newImgNumber]) != -1)
{
newImgNumber = Math.round(Math.random() * 3);
}
Next, you set the src property of the img object to the new value contained in your myImages array.
You r e t u r n false to stop the link from trying to navigate to another page; remember that the HTML
link is only there to provide a means of capturing an onclick event handler.
that.src = myImages[newImgNumber];
return false;
}
Now you connect the onclick event of the fi rst <img/> element to the changeImg() function:
<img name=img0 src=”usa.gif” border=”0” onclick=”return changeImg(this)”>
And now to the second <img/> element:
<img name=”img1” src=”mexico.gif” border=”0” onclick=”return changeImg(this)”>
Passing this in the changeImg() function gives the function direct access to this <img/> element's
corresponding object. When you pass this to an HTML element's attribute event handler, the corre-
sponding object of that element is passed to the function. It's a nice, clean way of accessing the element's
object in your JavaScript code.
Events are an important matter for web developers — your authors wager that a good bulk of your code will
handle events. Chapter 12 covers events again, but let's switch gears to another topic: the user's browser.
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 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 their browser.
Although you can go a long way with cross-browser-compatible code, there may come a time when you
want to add extra features that only one browser supports. The solution is to write script that determines
the user's browser and executes script that is compatible with the browser.
You can check for browser details in two main ways. The fi rst is to see if the object and property you
use in your code are actually available in the user's browser. Let's say for example that your code relies
on the all collection of the document object in Internet Explorer (IE). If you write
if (window.all)
{
Search WWH ::




Custom Search