Browse DevX
Sign up for e-mail newsletters from DevX


Essential JavaScript: 8 Cross-Browser Solutions-3 : Page 3

There's a core set of problems that every JavaScript developer will run across sooner or later. This article shows you how to deal with eight of the most common situations.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 <div> 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 <div> 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.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date