Essential JavaScript: 8 Cross-Browser Solutions

here’s a core set of problems that every JavaScript developer will run across sooner or later. In my Web Developer classes, I’ve noticed that some questions arise repeatedly—they’re common problems. The answers to these problems aren’t readily apparent from studying the language itself, because they’re not directly related to JavaScript—they’re browser and HTML-dependent problems. This article shows you how to deal with eight of the most common situations. Even if you don’t need them today, file them away to form the beginnings of your core library of cross-browser JavaScript.

Sniffing the Browser

Learn to recognize these and similar situations because you’re likely to encounter them repeatedly. All of these solutions are cross-browser scripts that have been tested in Internet Explorer 4+, Netscape 4.x, and Netscape 6.

Sniffing the Browser
Problem 1: How do I determine which browser a person is using?

Believe it or not, determining the browser isn’t all that important. What is important is what objects the browser supports. There are plenty of browser sniffers out there that use the navigator object to determine the exact browser manufacturer and version. The problem with all of those navigator-based sniffers is that if the browser maker changes the settings the sniffer will fail. Instead, use object detection to make your scripts forward compatible:

   if (document.layers){      //Netscape 4 specific code   }   if (document.getElementById){      //Netscape 6 specific code   }   if (document.all){      //IE4+ specific code   }

Even though IE5 supports the getElementById() function, if you are careful with your code, you can force IE5 to run only the appropriate code (see the next topic Writing Cross-Browser Scripts).

Writing Cross-Browser Scripts
Problem 2: I want to write one script that works in all three major browsers: NS4, NS6, IE4+. What can I do?

Most browser incompatibilities derive from the fact that different browsers refer to objects differently. Now that you know how to determine the browser type (see the previous topic Sniffing the Browser), you can use variables to hide the differences in object variables between browsers. For example, the following script creates “pre” and “post” variables to disguise DOM access differences between the browsers.

   if (document.layers){      //Netscape 4 specific code      pre = 'document.';      post = '';   }   if (document.getElementById){      //Netscape 6 specific code      pre = 'document.getElementById("';      post = '").style';   }   if (document.all){      //IE4+ specific code      pre = 'document.all.';      post = '.style';   }

Note that because IE5 supports both getElementById(), and document.all(), the pre and post variables are set twice—once during the document.getElementByID test and again in the document.all test. After setting the pre and post variables, you can reference objects in all three browsers using a simple eval() statement. For example:

   var myLayer = eval(pre + 'someLayerID' + post);   myLayer.left = 200;

The preceding code uses the pre and post variables to retrieve a reference to a

object whose id is set to “someLayerID”. Note that the post variable causes the code to return either a style object (Netscape 6 and IE4+) or the

element itself (Netscape 4). The last line sets the left property to 200. By hiding the object differences, it makes no difference which browser executes the code.

Determining Display Characteristics
Problem 3: How can I find out my users’ screen resolution? How can I determine the width and height of the browser window?

Two simple calls reveal the user’s screen resolution in all three browsers:

   var screenH = screen.height;   var screenW = screen.width;

However, the space you can use within a browser isn’t the same as the screen resolution, even when the browser window is maximized—and users may be running the browser in an unmaximized window. Determining the browser’s available width isn’t as straightforward. IE4+ uses a proprietary property while both Netscape versions favor the W3C’s standard properties:

   if(document.all){      availW = document.body.clientWidth;      availH = document.body.clientHeight;   }else{      availW = innerWidth;      availH = innerHeight;   }

To make matters worse, because IE uses properties of the document object (rather than the window object as in Netscape) you can’t get the available space until after the document loads. You have to fire the code in the onLoad event (or later) to get meaningful results.

Creating Image Rollovers
Problem 4: I want to create those cool buttons whose appearance changes when the mouse moves over them. How do I do that?

Image rollovers are probably the most widely used scripts on the Web. Implementing them is as simple as changing the src attribute of an element when the mouse moves over the image:

         

Then in your script:

   function on(img){      document[img].src = img + 'On.gif';   }   function off(img){      document[img].src = img + 'Off.gif';   }

When the user moves the mouse into or out of the image area, the anchor tag calls either the on or off function, passing a reference to the associated image as the img argument. The on and off functions swap the src attribute value to the appropriate image. Note that the element is required only due to Netscape 4’s inability to access an element’s src attribute directly (it doesn’t recognize the events in the element)—you don’t need the anchor tag in Netscape 6 or in IE.

Now that you’ve seen this explicit version, you should try implementing a slightly more complex version that combines the on() and off() functions into a single JavaScript function. (Hint—pass two arguments—the image object and the src).

Preloading Images
Problem 5: I’ve created rollover buttons but there is a noticeable delay before the rollover occurs. How do I get rid of the delay?

Preload your images in memory to avoid a return trip to the server for the new image. To preload images, declare a JavaScript image object and set its src property to the URL of the image. Doing this creates an image stored off screen in memory—often called an image buffer. Then, use the image object to swap the buffered image rather than the actual file:

   var aboutOn = new Image();   aboutOn.src = 'aboutOn.gif';   var aboutOff = new Image();   aboutOff.src = 'aboutOff.gif';      function on(img){   document[img].src = eval(img + 'On').src;   }      function off(img){   document[img].src = eval(img + 'Off').src;   }

When you place the script in the section of a document, the browser will load the images into memory before processing the element. Be careful, though—the more images you preload, the longer it will take your users to see any content at all.

Making a JumpList Combo Box
Problem 6: How do I create a drop down box with hyperlinks attached to each member of the list box so that clicking an item causes the browser to navigate to the associated link?

There are a number of ways to create a JumpList box, ranging from using arrays to managing the links directly in the drop down box. Here are the extremes:

   Using Arrays and Object Oriented Programming:         JumpList                     

The preceding code uses a jumpArray constructor, (for more on objects and constructors, see Creating Classy Menus with JavaScript to instantiate two JumpArrays--one for the labels and one for the urls. It also includes a goSearch function (since all of the urls point to search engines) called in the element:

         JumpList 2             

This one looks substantially easier, because the only JavaScript is located in the onChange event for the Password

You use the form's onSubmit attribute to intercept form submission. The example calls the canSubmit function and passes the form itself to the function. If the canSubmit function returns true, the form is submitted. If it returns false, the submission is interrupted and the user is prompted to enter something in the appropriate field. Admittedly, you'll want a better mechanism for logging in to sensitive areas but you get the idea.

These scripts are among those most requested by students in my classes. In the form I've presented them here (aside from the form validation), the scripts are components from which you can build web applications that are compatible with all three major browsers. Next month, I'll discuss form validation with the depth it deserves.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: