Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Workshop: Scripting for Multiple Browsers

As an example of the techniques you learned in this hour, you can create a script that uses reliable methods to determine which of the following categories the current browser falls into:

This is useful because the 5.0 and later browsers support the new DOM for dynamic HTML. You may also want to support the 4.x browsers, which support dynamic features but in incompatible ways. Last but not least, older browsers can be supported with a minimal script.

As a simple example, this script will determine the browser in use and set a variable, browser, to the appropriate code. Listing 14.2 shows the browser detection example.

Example 14.2. The browser detection example

<html>
<head>
<title>Browser Detection</title>
<script language="Javascript" type="text/javascript">
// check for 5.0 or later browsers
if (parseInt(navigator.appVersion) >= 5
   || navigator.appVersion.indexOf("MSIE 5") != -1) {
   browser="DOM";
} else if (navigator.userAgent.indexOf("Mozilla/4") != -1)
   {
   if (navigator.appName.indexOf("Netscape") != -1)
      browser="NS4";
   if (navigator.appVersion.indexOf("MSIE 4") != -1)
      browser="IE4";
  } else browser="Other";
</script>
</head>
<body>
<h1>Browser Detection Example</h1>
<script language="Javascript" type="text/javascript">
document.write("browser detected: " + browser + "<br>");
</script>
</body>
</html>

The script in the header of this document assigns the variable browser the value of DOM for 5.0 browsers, NS4 for Netscape 4.x, and IE4 for Internet Explorer 4.x. The body of this document simply displays the variable, but your script could use it to change the output according to the browser.

Share ThisShare This

Informit Network