A Complete Guide to Web Design

(やまだぃちぅ) #1
384 Chapter 22 – Introduction to JavaScript

Handling Multiple Browsers


Web Design in a Nutshell, eMatter Edition

else if (bName == "Microsoft Internet Explorer" && bVer >= 4)
br = "e4";
else if (bName == "Microsoft Internet Explorer") br = "e3";
else br = "n2";
This code puts the name of the browser in a variable calledbNameand the version
number in a variable calledbVer. Depending on the name and number in these
variables, the variable br is assigned a value corresponding to the different
browsers. Thus, if the browser is Netscape 4,bris set ton4; if the browser is IE 4,
bris set toe4. After the browser identity has been assigned to this variable, you
use if/else statements to write the code:
if br=n4 {
//Netscape 4-specific JavaScript goes here
}

else if br=e4 {
//IE-4 specific code goes here
}
//-->
</SCRIPT>
</HEAD>
In this code, the firstifstatement checks to see if the browser is Netscape 4; if it
is, it runs the Netscape-4 specific code. If it’s not Netscape 4, the code checks for
IE4; if it’s IE4, the appropriate code is run. If it’s neither of these browsers, no
script is run and the body of the HTML document is displayed normally.
<BODY>
//Standard HTML code goes here
</BODY>
</HTML>
Of course in most JavaScript documents, the script is invoked within the HTML.
For instance, an anchor tag may invoke a JavaScript when the mouse is placed
over a link:
<HTML>
<HEAD>
<TITLE>A Page</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!—
bName=navigator.appName;
bVer=parseInt(navigator.appVersion);
if ((bName=="Netscape" && bVer>=3) ||
(bName=="Microsoft Internet Explorer" && bVer>=4)) br="n3";
else br="n2";
//-->
</SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<A HREF="home.html" onMouseOver="document.home.src='home_on.gif';">
<IMG BORDER=0 HEIGHT=35 WIDTH=111 NAME="home" SRC="home_off.gif"></A>
</BODY>
</HTML>
Free download pdf