Categories
JavaScript

Netscape Navigator’s JavaScript 1.1 vs Microsoft Internet Explorer’s JScript

Originally appeared in Digital Cats magazine. Found courtesy Wayback Machine.

Prior to Netscape implementing JavaScript in Netscape Navigator, web developers had few tools to create interactive content for their web pages. Now this scripting language gives developers the ability to do things such as check form contents, communicate with the user based on their actions, and modify the web page dynamically without the web page being re-loaded and without the use of Java, plug-ins or ActiveX controls.

Unfortunately, JavaScript was not usable by any other browser until Microsoft released Internet Explorer (IE) 3.0. With this release web developers could deliver interactive content that would at least work with the two most widely used browsers. Or could they?

On the surface, the JavaScript supported by both companies is identical. They both provide the same conditional control statements, have defined objects such as window or document,and can be used directly in HTML documents. They both support events based on user actions and support functions in a similar manner. However, this article will demonstrate that though the languages may look the same on the surface, there are differences that can trip the unwary developer.

JavaScript Objects

To understand the differences between the two implementations of JavaScript you must examine the objects both support. As an example, with Navigator 3.0 Netscape provides a new object image which is an array (defined as images that contains the images in the document currently loaded. This object allows the developer to change the images of a document without re-loading the document or using Java or other technique. With this capability the developer can write the following JavaScript code section without error:


sSelected = "http://www.some.com/some.gif"
document.images[iIndex].src = sSelected

This code will change the src property of the image that is contained in the array at the index given in the variable iIndex. If this variable contained the value 2, the 3rd image as loaded in the document (the array indices begin at 0) would be changed to the image located in the given URL. An example using images can be found here.

Running the same example with Internet Explorer will result in a alert message that states that “‘images’ is not an object”.

Other examples of objects that are defined for Netscape Navigator but not for Microsoft Internet Explorer are:

  • The Area object, which is an array of links for an image map that allows the developer to capture certain events for the image map that can be used to provide additional information to the user. With this, the developer can capture a mouseOver event to write out information about the link in the status bar.
  • The FileUpload object which provides a text like control and a button marked with “Browse” that will allow a reader to enter a file name. The JavaScript can then access the name of the file.
  • The Function object which allows the developer to define and assign a function to a variable which can then be assigned to an event.
  • The mimeTypes Array of supported MIME types.
  • The option object which is an array of the options implemented for SELECT and which allows the developer to change the text of the option at runtime
  • The applet object, which is an array of Applets in the document (read-only)
  • The plugin object, which is an array called embeds that contains the plug-ins contained in the document (read-only)
  • The plugins array, which is an array of plug-ins currently installed in the client browser

At this time there are no JavaScript or JScript objects defined for Internet Explorer that are also not defined for Netscape. However, as JScript is an implementation script for IE and Microsoft has defined their own IE scripting model, this could change in the future.

JavaScript Object Behavior and Ownership

Internet Explorer may not have additional objects but it has defined a different hierarchy and ownership for some of the objects that are used by both it and Navigator. All objects are contained within the window object in the IE scripting model, which can be viewed here, but not all objects are owned by window with the Navigator model, which can be viewed with the JavaScript Authoring Guide. The object Navigator, which is the object that stores information about the browser currently being used, is an example of an owned object by window in IE but not in Navigator.

This will not present an incompatibility problem between the two browsers as the developer will usually not preface the object with the term “window” as the following code demonstrates:


<FORM NAME="form1">
<input type=button value='press' onClick="alert(navigator.appName)">
</FORM>

The above code will work with both browsers.

The differences between the ownership can become a problem when an object is owned by different levels of objects. An example is the history object, which is owned by the window object in IE, but by the document object in Navigator. When used in the current window and document, the object will work the same as the following code will demonstrate:


<FORM NAME="form1">
<input type=button value='press' onClick="history.back()">
</FORM>
 

The reason the same code can work for both is that window is assumed for both IE and Netscape and document is assumed for Navigator, at least in this instance because history is also an object in its own right. In the case of a document being opened as part of a frame, the differences then become noticeable. The following code will work when the document is opened as a frame in IE, but will not work in Navigator:


<body>
<script>
function clicked() {
history.back()
}
</script>
<FORM NAME="form1">
<input type=button value='press' onClick="clicked()">
</FORM>
</body>

Clicking on the button from the code above will work for IE. The previous document in the History list will be opened, but the same code will not work for Navigator. Clicking on the button will result in neither a change of document nor an error. Prefacing the history object with parent will enable this code to work with both browsers.

JavaScript Properties

Even when IE and Navigator share a common object and a common object ownership, they can differ on the properties for an object. An example is the document object. The properties for both implementations are the same except for an URL property for the Navigator implementation and a location property for the IE implementation. However, if you examine both properties, they are identical! Both contain the URL of the document. Both are read-only. The following code will work with Navigator, but results in an empty Alert message box for IE:


<FORM NAME="form1">
<input type=button value='press' onClick="alert(document.URL)">
</FORM>

According to Microsoft documentation, the equivalent for IE would be to use document.location.href. However, though this does not result in an error, it also results in an empty alert box. The following code achieves the desired results and, happily, works in both browsers:


<FORM NAME="form1">
<input type=button value='press' onClick="alert(location.href)">
</FORM>

The above example does demonstrate another area of caution when using the JavaScript language: this language is unstable in both environments and is changing continuously. Don’t assume something will work because the documentation states it will, and don’t assume it will work the same on all operating systems. Both browsers can have different behaviors across different operating systems, sometimes because of operating system differences and sometimes because of bugs that were missed during testing on that specific OS.

JavaScript Methods and Events

A web developer can find ways of working around differences in objects and properties, but working around differences in methods may not be so easy. When we develop we expect a certain behavior to result when we call a specific function and pass to it certain parameters. With Microsoft Internet Explorer and Netscape Navigator, the best case scenario is that we can use a pre-defined object method with both browsers and have the same result. The worst case scenario is that the method works with both browsers, but the result is different.

An example of the best case scenario is to use JavaScript to validate form field contents which have changed or to use these contents to calculate a value used elsewhere. Calling a JavaScript function from the onChange event to process the changed contents as demonstrated below will work with both browsers:


<!--- Form fields
<p>Item Quantity: <INPUT TYPE="text" Name="qty">
Item Cost: <INPUT TYPE="text" Name="cost"
                onChange="NewCost()">
Total Cost: <INPUT TYPE="text" Name="total" Value=0>
…
<!--- Function
<SCRIPT LANGUAGE="javascript">
<!--- hide script from old browsers

// NewCost will
// calculate cost of qty and item
function NewCost() {
        var iCost = parseFloat(document.Item.cost.value)
        var iQty = parseInt(document.Item.qty.value)

        var iTotal = iCost * iQty
        document.Item.total.value = iTotal
        }

The above will work as expected with both IE and Navigator. When the user enters a quantity and a cost, the onChange event will fire for the cost field and a JavaScript function called NewCost() will be called. This function will call two built-in JavaScript functions, parseFloat() and parseInt(), to access and convert the form field values. These will then be used to compute a total which is placed in the total field.

So far so good. Another JavaScript function in the web page will be processed when the user presses the submit button. This pre-defined button style will normally submit the form. The developer can capture the submission and perform validation on the fields. Coding this for Navigator would look like the following:


<FORM NAME="Item"
        ACTION="some.cgi" onSubmit="return SendOrder()">
…
<!--- Function
// submit order
function SendOrder() {

        // validate data
        if (document.Item.Name.value == "") {
                alert("You must enter your name")
                return false
                }
        return true
        }

Capturing the onSubmit event will allow the developer to call a function to process the form fields. If they choose, they can perform validation in this function. If the validation fails, say the user did not provide a name, the function notifies the reader and returns false, preventing the form from being submitted. If the user did provide a name, the function would return true, and the form would be submitted.

Following the documentation that can be found at the Microsoft site, the developer would expect something like this to work for IE as well as Navigator. It does, to a point.

With IE the onSubmit event is captured and the SendOrder() function is called. If the user did not enter a name value, an alert would occur. The behavior is the same for both browsers at this point. However, if the user does provide a value, Navigator would then submit the form and a follow-up form would be displayed. This does NOT occur with IE IF you are testing the page locally, probably due to a bug missed during the testing. It does work if you run the web page documents through a web server.

However, without knowing that the difference between the two results was a matter of document location rather than document coding the web page developer could have spent considerable time trying to get the same behavior for both browsers.

Aside from the differences already noted, the browsers may process code in a funtionally identical manner and yet perform quite differently. This can be demonstrated with another popular use of JavaScript which is to open a secondary window for some purpose and to maintain communication between the two windows. This is widely used by Netscape for their tutorials.

Both browsers support a property for the window object called opener. This property can be used to contain a reference to the window that opened the secondary window.

The following code demonstrates using JavaScript to open a secondary window and to set the opener property to the original window:


<HTML>
<HEAD><TITLE> Original Window </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--- hide script from old browsers
// OpenSecondary will open a second window
//
function OpenSecond(iType, sMessage) {
        // open window
        newWindow=window.open("second.htm","",
                "toolbar=no,directories=no,width=500,height=300")
        // modify the new windows opener value to
        // point to this window
        if (newWindow != null && newWindow.opener == null)
                newWindow.opener=window

        }
// end hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<H1> Open a new Window and get information</H1>

<FORM NAME="CallWindow">
<p>Click to open Window:
<p>
<INPUT TYPE="button" NAME="OpenWin" VALUE="Click Here"
        onClick="OpenSecond()">
<p>
</FORM>
</BODY>
</HTML>

The above HTML and JavaScript creates a simple document with one button. Pressing the button opens a new window (creates a new instance of the browser) that does not have a toolbar or directories and is set to a certain width and height. The HTML source document that is opened into this new window is “second.htm”.

The HTML and JavaScript in the secondary window is shown below:


<HTML>
<HEAD><TITLE> Information</TITLE>

<SCRIPT LANGUAGE="JavaScript">
<!--- hide script from old browsers
// SetInformation
// function will get input values
// and set to calling window
function SetInformation() {
        opener.document.open()
        opener.document.write("<BODY>")
        opener.document.write("<H1> Return from Secondary</h1>")
        opener.document.write("</BODY>")
        opener.document.close()
        opener.document.bgColor="#ff0000"
        window.close()
        }
// end hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<p><form>
Click on the button:<p>
<INPUT type="button" Value="Click on Me"
     onClick="SetInformation()">
</CENTER>
</FORM>
</BODY>
</HTML>

This code will display a button labeled “Click on Me”. Pressing this button will result in the document page for the original window being modified to display the words “Return from Secondary”. The JavaScript will also change the background color of the original document and then will close the secondary window. When run in Navigator, the sample behaves as expected. Not so, however, with IE.

First, when you open the secondary window in IE you will notice that the document in the original window seems to blank out for a moment. In addition, the secondary window opens at the top left hand side of the desktop with IE but opens directly over the original window with Navigator, no matter where that original window is.

When you press the button that modifies the original document, IE does modify the document with the new header, as Navigator does, and the background on the original document will change briefly. However, when the secondary window is closed the background color of the original document returns to the original color!

What is worse is that running this sample for a few times with IE will cause the browser to crash! How soon it will crash seems to suggest that resources are not being freed, or are being freed incorrectly. Whatever the cause, this behavior should make a developer feel cautious about opening up a secondary window within IE.

Solutions to working with both Internet Explorer and Navigator

JavaScript is a useful tool for creating interactive content without using Java or some other technique. As we have seen, problems arise out of the incompatibility between Navigator and IE. What are ways to avoid these problems?

  • Code for one browser only. This is not really a viable solution. While Netscape Navigator is the most popular browser in use today, Microsoft Internet Explorer is gaining quite a following. Using Navigator-only JavaScript that will limit your web page’s audience.
  • Code only to the least common denominator. By limiting the JavaScript to that which works for both Navigator and IE, developers will have access to most of the functionality they need. However, with this approach developers will need to be aware of the gotchas that have been discussed in this article. In other words, the developer has to test with both browsers; the tests will have to occur via the web server as well as run locally; the tests should be repeated several times to ensure that no adverse effects show up over time; the code should be tested with all possible environments.
  • Code for each browser within the same page. This is actually my favorite approach though it will require more effort by the developer. Both browsers will process JavaScript labeled as <SCRIPT LANGUAGE=”javascript”>, however only Navigator will process script labeled as <SCRIPT LANGUAGE=”javascript1.1″>. With this approach, the developer can place JavaScript common to both browsers in a SCRIPT tag labeled with “javascript” and Navigator specific code in a SCRIPT tag labeled with “javascript1.1”. To add in IE specific code, the developer would probably want to use VBScript code or use the tag JScript whenever applicable. At this time, JScript is implemented for scripting with events only, not as a language specification for the SCRIPT tag.

Summary

JavaScript is a very effective tool, and a relatively simple method for adding interactive content to a web page. With version 3.0 of Internet Explorer, using JavaScript is viable for both of the most popular browsers in use. However, developersneeds to be aware of the differences between Netscape Navigator and Microsoft Internet Explorer and should test thoroughly with both before posting the page to their site.

Categories
JavaScript

Netscape Navigator’s JavaScript 1.1 vs Microsoft Internet Explorer’s JScript

Originally published at Digital Cats, now archived at the Wayback Machine

Prior to Netscape implementing JavaScript in Netscape Navigator, web developers had few tools to create interactive content for their web pages. Now this scripting language gives developers the ability to do things such as check form contents, communicate with the user based on their actions, and modify the web page dynamically without the web page being re-loaded and without the use of Java, plug-ins or ActiveX controls.

Unfortunately, JavaScript was not usable by any other browser until Microsoft released Internet Explorer (IE) 3.0. With this release web developers could deliver interactive content that would at least work with the two most widely used browsers. Or could they?

On the surface, the JavaScript supported by both companies is identical. They both provide the same conditional control statements, have defined objects such as window or document,and can be used directly in HTML documents. They both support events based on user actions and support functions in a similar manner. However, this article will demonstrate that though the languages may look the same on the surface, there are differences that can trip the unwary developer.

JavaScript Objects

To understand the differences between the two implementations of JavaScript you must examine the objects both support. As an example, with Navigator 3.0 Netscape provides a new object image which is an array (defined as images that contains the images in the document currently loaded. This object allows the developer to change the images of a document without re-loading the document or using Java or other technique. With this capability the developer can write the following JavaScript code section without error:


sSelected = "http://www.some.com/some.gif"
document.images[iIndex].src = sSelected

This code will change the src property of the image that is contained in the array at the index given in the variable iIndex. If this variable contained the value 2, the 3rd image as loaded in the document (the array indices begin at 0) would be changed to the image located in the given URL. An example using images can be found here.

Running the same example with Internet Explorer will result in a alert message that states that “‘images’ is not an object”.

Other examples of objects that are defined for Netscape Navigator but not for Microsoft Internet Explorer are:

  • The Area object, which is an array of links for an image map that allows the developer to capture certain events for the image map that can be used to provide additional information to the user. With this, the developer can capture a mouseOver event to write out information about the link in the status bar.
  • The FileUpload object which provides a text like control and a button marked with “Browse” that will allow a reader to enter a file name. The JavaScript can then access the name of the file.
  • The Function object which allows the developer to define and assign a function to a variable which can then be assigned to an event.
  • The mimeTypes Array of supported MIME types.
  • The option object which is an array of the options implemented for SELECT and which allows the developer to change the text of the option at runtime
  • The applet object, which is an array of Applets in the document (read-only)
  • The plugin object, which is an array called embeds that contains the plug-ins contained in the document (read-only)
  • The plugins array, which is an array of plug-ins currently installed in the client browser

At this time there are no JavaScript or JScript objects defined for Internet Explorer that are also not defined for Netscape. However, as JScript is an implementation script for IE and Microsoft has defined their own IE scripting model, this could change in the future.

JavaScript Object Behavior and Ownership

Internet Explorer may not have additional objects but it has defined a different hierarchy and ownership for some of the objects that are used by both it and Navigator. All objects are contained within the window object in the IE scripting model, which can be viewed here, but not all objects are owned by window with the Navigator model, which can be viewed with the JavaScript Authoring Guide. The object Navigator, which is the object that stores information about the browser currently being used, is an example of an owned object by window in IE but not in Navigator.

This will not present an incompatibility problem between the two browsers as the developer will usually not preface the object with the term “window” as the following code demonstrates:


<FORM NAME="form1">
<input type=button value='press' onClick="alert(navigator.appName)">
</FORM>

The above code will work with both browsers.

The differences between the ownership can become a problem when an object is owned by different levels of objects. An example is the history object, which is owned by the window object in IE, but by the document object in Navigator. When used in the current window and document, the object will work the same as the following code will demonstrate:


<FORM NAME="form1">
<input type=button value='press' onClick="history.back()">
</FORM>

The reason the same code can work for both is that window is assumed for both IE and Netscape and document is assumed for Navigator, at least in this instance because history is also an object in its own right. In the case of a document being opened as part of a frame, the differences then become noticeable. The following code will work when the document is opened as a frame in IE, but will not work in Navigator:


<body>
<script>
function clicked() {
history.back()
}
</script>
<FORM NAME="form1">
<input type=button value='press' onClick="clicked()">
</FORM>
</body>

Clicking on the button from the code above will work for IE. The previous document in the History list will be opened, but the same code will not work for Navigator. Clicking on the button will result in neither a change of document nor an error. Prefacing the history object with parent will enable this code to work with both browsers.

JavaScript Properties

Even when IE and Navigator share a common object and a common object ownership, they can differ on the properties for an object. An example is the document object. The properties for both implementations are the same except for an URL property for the Navigator implementation and a location property for the IE implementation. However, if you examine both properties, they are identical! Both contain the URL of the document. Both are read-only. The following code will work with Navigator, but results in an empty Alert message box for IE:


<FORM NAME="form1">
<input type=button value='press' onClick="alert(document.URL)">
</FORM>

According to Microsoft documentation, the equivalent for IE would be to use document.location.href. However, though this does not result in an error, it also results in an empty alert box. The following code achieves the desired results and, happily, works in both browsers:


<FORM NAME="form1">
<input type=button value='press' onClick="alert(location.href)">
</FORM>

The above example does demonstrate another area of caution when using the JavaScript language: this language is unstable in both environments and is changing continuously. Don’t assume something will work because the documentation states it will, and don’t assume it will work the same on all operating systems. Both browsers can have different behaviors across different operating systems, sometimes because of operating system differences and sometimes because of bugs that were missed during testing on that specific OS.

JavaScript Methods and Events

A web developer can find ways of working around differences in objects and properties, but working around differences in methods may not be so easy. When we develop we expect a certain behavior to result when we call a specific function and pass to it certain parameters. With Microsoft Internet Explorer and Netscape Navigator, the best case scenario is that we can use a pre-defined object method with both browsers and have the same result. The worst case scenario is that the method works with both browsers, but the result is different.

An example of the best case scenario is to use JavaScript to validate form field contents which have changed or to use these contents to calculate a value used elsewhere. Calling a JavaScript function from the onChange event to process the changed contents as demonstrated below will work with both browsers:


<!--- Form fields
<p>Item Quantity: <INPUT TYPE="text" Name="qty">
Item Cost: <INPUT TYPE="text" Name="cost"
                onChange="NewCost()">
Total Cost: <INPUT TYPE="text" Name="total" Value=0>
…
<!--- Function
<SCRIPT LANGUAGE="javascript">
<!--- hide script from old browsers

// NewCost will
// calculate cost of qty and item
function NewCost() {
        var iCost = parseFloat(document.Item.cost.value)
        var iQty = parseInt(document.Item.qty.value)

        var iTotal = iCost * iQty
        document.Item.total.value = iTotal
        }

The above will work as expected with both IE and Navigator. When the user enters a quantity and a cost, the onChange event will fire for the cost field and a JavaScript function called NewCost() will be called. This function will call two built-in JavaScript functions, parseFloat() and parseInt(), to access and convert the form field values. These will then be used to compute a total which is placed in the total field.

So far so good. Another JavaScript function in the web page will be processed when the user presses the submit button. This pre-defined button style will normally submit the form. The developer can capture the submission and perform validation on the fields. Coding this for Navigator would look like the following:


<FORM NAME="Item"
        ACTION="some.cgi" onSubmit="return SendOrder()">
…
<!--- Function
// submit order
function SendOrder() {

        // validate data
        if (document.Item.Name.value == "") {
                alert("You must enter your name")
                return false
                }
        return true
        }

Capturing the onSubmit event will allow the developer to call a function to process the form fields. If they choose, they can perform validation in this function. If the validation fails, say the user did not provide a name, the function notifies the reader and returns false, preventing the form from being submitted. If the user did provide a name, the function would return true, and the form would be submitted.

Following the documentation that can be found at the Microsoft site, the developer would expect something like this to work for IE as well as Navigator. It does, to a point.

With IE the onSubmit event is captured and the SendOrder() function is called. If the user did not enter a name value, an alert would occur. The behavior is the same for both browsers at this point. However, if the user does provide a value, Navigator would then submit the form and a follow-up form would be displayed. This does NOT occur with IE IF you are testing the page locally, probably due to a bug missed during the testing. It does work if you run the web page documents through a web server.

However, without knowing that the difference between the two results was a matter of document location rather than document coding the web page developer could have spent considerable time trying to get the same behavior for both browsers.

Aside from the differences already noted, the browsers may process code in a funtionally identical manner and yet perform quite differently. This can be demonstrated with another popular use of JavaScript which is to open a secondary window for some purpose and to maintain communication between the two windows. This is widely used by Netscape for their tutorials.

Both browsers support a property for the window object called opener. This property can be used to contain a reference to the window that opened the secondary window.

The following code demonstrates using JavaScript to open a secondary window and to set the opener property to the original window:


<HTML>
<HEAD><TITLE> Original Window </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--- hide script from old browsers
// OpenSecondary will open a second window
//
function OpenSecond(iType, sMessage) {
        // open window
        newWindow=window.open("second.htm","",
                "toolbar=no,directories=no,width=500,height=300")
        // modify the new windows opener value to
        // point to this window
        if (newWindow != null && newWindow.opener == null)
                newWindow.opener=window

        }
// end hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<H1> Open a new Window and get information</H1>

<FORM NAME="CallWindow">
<p>Click to open Window:
<p>
<INPUT TYPE="button" NAME="OpenWin" VALUE="Click Here"
        onClick="OpenSecond()">
<p>
</FORM>
</BODY>
</HTML>

The above HTML and JavaScript creates a simple document with one button. Pressing the button opens a new window (creates a new instance of the browser) that does not have a toolbar or directories and is set to a certain width and height. The HTML source document that is opened into this new window is “second.htm”.

The HTML and JavaScript in the secondary window is shown below:


<HTML>
<HEAD><TITLE> Information</TITLE>

<SCRIPT LANGUAGE="JavaScript">
<!--- hide script from old browsers
// SetInformation
// function will get input values
// and set to calling window
function SetInformation() {
        opener.document.open()
        opener.document.write("<BODY>")
        opener.document.write("<H1> Return from Secondary</h1>")
        opener.document.write("</BODY>")
        opener.document.close()
        opener.document.bgColor="#ff0000"
        window.close()
        }
// end hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<p><form>
Click on the button:<p>
<INPUT type="button" Value="Click on Me"
     onClick="SetInformation()">
</CENTER>
</FORM>
</BODY>
</HTML>

This code will display a button labeled “Click on Me”. Pressing this button will result in the document page for the original window being modified to display the words “Return from Secondary”. The JavaScript will also change the background color of the original document and then will close the secondary window. When run in Navigator, the sample behaves as expected. Not so, however, with IE.

First, when you open the secondary window in IE you will notice that the document in the original window seems to blank out for a moment. In addition, the secondary window opens at the top left hand side of the desktop with IE but opens directly over the original window with Navigator, no matter where that original window is.

When you press the button that modifies the original document, IE does modify the document with the new header, as Navigator does, and the background on the original document will change briefly. However, when the secondary window is closed the background color of the original document returns to the original color!

What is worse is that running this sample for a few times with IE will cause the browser to crash! How soon it will crash seems to suggest that resources are not being freed, or are being freed incorrectly. Whatever the cause, this behavior should make a developer feel cautious about opening up a secondary window within IE.

Solutions to working with both Internet Explorer and Navigator

JavaScript is a useful tool for creating interactive content without using Java or some other technique. As we have seen, problems arise out of the incompatibility between Navigator and IE. What are ways to avoid these problems?

  • Code for one browser only. This is not really a viable solution. While Netscape Navigator is the most popular browser in use today, Microsoft Internet Explorer is gaining quite a following. Using Navigator-only JavaScript that will limit your web page’s audience.
  • Code only to the least common denominator. By limiting the JavaScript to that which works for both Navigator and IE, developers will have access to most of the functionality they need. However, with this approach developers will need to be aware of the gotchas that have been discussed in this article. In other words, the developer has to test with both browsers; the tests will have to occur via the web server as well as run locally; the tests should be repeated several times to ensure that no adverse effects show up over time; the code should be tested with all possible environments.
  • Code for each browser within the same page. This is actually my favorite approach though it will require more effort by the developer. Both browsers will process JavaScript labeled as <SCRIPT LANGUAGE=”javascript”>, however only Navigator will process script labeled as <SCRIPT LANGUAGE=”javascript1.1″>. With this approach, the developer can place JavaScript common to both browsers in a SCRIPT tag labeled with “javascript” and Navigator specific code in a SCRIPT tag labeled with “javascript1.1”. To add in IE specific code, the developer would probably want to use VBScript code or use the tag JScript whenever applicable. At this time, JScript is implemented for scripting with events only, not as a language specification for the SCRIPT tag.

Summary

JavaScript is a very effective tool, and a relatively simple method for adding interactive content to a web page. With version 3.0 of Internet Explorer, using JavaScript is viable for both of the most popular browsers in use. However, developersneeds to be aware of the differences between Netscape Navigator and Microsoft Internet Explorer and should test thoroughly with both before posting the page to their site.

Categories
JavaScript Technology

Using Dynamic HTML to create an animated menubar

Originally published in Netscape World, now archived at the Wayback Machine

Microsoft and Netscape decided to use two different techniques for Dynamic HTML. Microsoft bases its approach on exposing CSS1 (Cascading Style Sheets) attributes to script, with a little help from some interesting new built-in, lightweight, and windowless ActiveX controls. Netscape bases much of its approach on the new LAYER tag.

At first glance, the approaches seem incompatible — using one browser’s techniques will not work with the other. However, you can use both browsers’ techniques within the same page and generate the exact same result.

In this article, I create an animated menu bar using a combination of CSS1 style sheets, the PATH ActiveX control, and dynamically modifying HTML elements to work with IE 4.0. I create the exact same effect using CSS1 style sheets and the LAYER tag for Navigator 4.0. Note, though, that both IE 4.0 and Navigator 4.0 are works in progress, and this example may need to be modified, slightly, for future versions of either product.

Creating style sheetsThe first section of the example page is the CSS1 style sheet settings. Both IE 4.0 and Navigator 4.0 process these style sheets, though Navigator does not seem to like setting images using the IMG tag at this time.

This example image uses headers for the text-based portion of a menu bar. To create the effect I want, I don’t want the standard underline that occurs with hypertext links, and I do want to modify the font size and color. As I don’t want either of these changes to impact on the rest of the document, I use the cascading effect of CSS1 to apply these changes only to links contained within <H2> header tags:

h2 A { text-decoration: none; color: gold } 
h2 A:link { color: gold } 
h2 A:visited { color: gold }

Next, I create the style sheet definitions for the menu images, for use with IE 4.0 only. I use absolute positioning to place the images exactly where I want on the page, and use the visibility property to hide the images when the page is first opened:

#menu1 { position: absolute; left: 0; top: 0; 
	visibility: hidden}
#menu2 { position: absolute; left: 142; top: 0; 
	visibility: hidden}
#menu3 { position: absolute; left: 284; top: 0; 
	visibility: hidden}
#menu4 { position: absolute; left: 192; top: 0; 
	visibility: hidden}
#menu5 { position: absolute; left: 142; top: 192;
	visibility: hidden }
#menu6 { position: absolute; left: 284; top: 192; 
	visibility: hidden}

The final part of the CSS1 style sheet definition creates the text-based menu components of the menu bar. These show as soon as the page is opened, and if the Web page reader does not want to wait for the images, or has image downloading turned off, they can access the links via the text menu. The size of the area for the menu text item should be large enough to contain the complete text, otherwise odd behavior will result with Internet Explorer: It does not display the text correctly when you click on a text-based menu item. Another text-based style sheet rule is provided for a message that is displayed while the images are loading. Whenever you create content that may be invisible or not displayed for a time, provide some kind of feedback to the user about what is happening:

This is the final section of the CSS style sheet definitions.

Adding images to a Web pageThe next section in the example page is the scripting, but I will talk about that a bit later. For now, I will add the images to the Web page using two different techniques, one for IE 4.0, and one for Navigator 4.0. IE 4.0 uses the style sheet settings defined for the images, and references the appropriate definition by using the identifier of the style sheet rule. The Navigator technique is to embed the images within layers that are hidden when the page first loads. IE 4.0 ignores the LAYER tag, and Navigator ignores the image style sheet rules:

Note that a hypertext link reference is applied to the image, and the border is set to 0. As the image style sheet rules seem to be ignored by Navigator, important image information such as widthheight, and border are specified within the image tag.

Next, the text objects are added to the menu bar. This includes a text-based alternative that labels each image when it is displayed, or can be accessed directly if the image is not displayed. This also includes a message stating that the images for the menu bar are being loaded:

The “waiting…” text is placed within a LAYER tag as I need to add script to modify it later, and only layer-based elements can be modified with Navigator at this time.

The final objects to add to the page are six ActiveX PATH objects, to control the menu bar animations for IE 4.0. A path object can be used to specify both X and Y coordinates at specific tick marks and moves the visual object associated with the control along that path. Two of the parameters for the control are the X path coordinates and the Y path coordinates. Another parameter could also control the timer, but I want to synchronize my image movement, so I use a different script-based approach later:

Notice that the X, Y coordinates for each path object are different, but all of them have the same number of timing ticks, which is the first parameter given in each of the coordinate pairings. The tick timings given are in microseconds.

The PATH ActiveX controls are the last elements placed into the page. Next comes the fun part, animating the menu bar.

Adding the script to animate the menu barThe animation is started when the page loads by trapping the onLoad event for the document. This calls a function called cycle. This function is implemented in both VBScript and JavaScript, and the appropriate browser picks the appropriate implementation, with Microsoft grabbing the VBscript version, Navigator grabbing the JavaScript version.

The first script controls the menu bar for IE 4.0. This is written entirely in VBScript, though JavaScript could be used if browser differences are handled correctly. The cycle function sets the Target properties of the path objects to the style sheet rules of the menu bar images. This associates each path control with its visual object. Next, the images are set to be visible, and the “waiting..” text is hidden.

The Play method for each path control is called, beginning the animation process, though no movement occurs yet. Why? No movement occurs because no timing mechanism has been associated with each control. The timing is handled by using the setTimeout function and calling a second subroutine that handles the image animation. The complete text of the cycle subroutine is here:

I use my own timer to synchronize the images, a technique that Microsoft recommends when using more than one PATH control on the same Web page.

The MoveIEObjects subroutine calls the Tick method for each of the path controls, moving each of the objects to the next coordinate defined for the specific control. It issues another setTimeout function call to continue the animation process, after first testing to see if the last movement of the path has occurred (the last of the ticks, of which there are eight for this particular demonstration). Note that I did not necessarily have to test the tick movement because after the path has completely played, it no longer moves unless it is rewound. However, I want to make sure the timer is not still operating. The complete text of MoveIEObjects is given next:

Next, I add the JavaScript to control the animation for Navigator 4.0. The cycle function for Navigator is similar to that for IE 4.0, except that I need to create my own arrays of X and Y coordinates. These arrays, in turn, are set to hold other arrays holding the actual coordinates. After the arrays are created, the images are displayed and the timer is started, as seen next:

The final script is for the MoveObjects function for Navigator. The LAYER tag method moveTo is used to move each of the images to the new coordinate for this timer event. Note that the timer values are set to be much larger than the ones set for IE 4.0 as the PATH control does run a bit slower than using the LAYER tag approach, and I wanted both effects to be as similar as possible. MoveObjects can be seen next:

Note that resizing Navigator can misalign the images. Netscape recommends a blank document.write statement in JavaScript to compensate for this type of problem, but this does not work for this example. I will continue to investigate this and will post a fix to my Web site when one appears. In the meantime, if you resize the Web page you need to reload the example. No problem occurs when you resize IE.

That’s it for the scripting. You can test the example yourself if you are using either IE 4.0 or Netscape 4 (this script will not work on earlier browsers). View the complete source by using the appropriate “View Source” option of your browser.

 

Categories
Technology

Adding dynamic content for multiple browsers & versions

Originally published in Netscape World May 1997, archived at Wayback Machine

One concern facing all Web developers when Microsoft or Netscape release a new version of Navigator or Internet Explorer is how to incorporate some of the new technologies of the new versions, but still offer Web pages that are readable by older versions of the browser. The developer could consider forcing those people who view their pages use the newer versions of the browser, but this approach limits your audience, something most Web sites want to avoid.

Neither is it feasible for a Web site to limit their pages to those viewable only by one browser. Microsoft Internet Explorer has been steadily gaining market share since the release of IE 3.0. Most Web sites will need to develop content that will work with at least two versions (the current released version, and the version that is in preview release) of each of the major browsers. The good news is that there are techniques to use to enable this cross-browser, cross-version capability. The bad news is that each of the techniques will require additional and, at times, extensive effort.

This article demonstrates two techniques to manage browser and version differences at a Web site. The first uses scripting to determine the type and version of the browser, and re-directs the browser to load a specific page. The second uses scripting and style sheet techniques to generate content, in one page, viewable by different browsers and versions. The article will also detail some rules of thumb to follow when creating a browser friendly Web site.

There is more than one way to re-direct browser input. One tactic is to create a separate Web page for each browser and each browser version that they want to support, and then have a CGI program load the appropriate Web page based on which browser and version is accessing the page. This is not a bad approach, and it works well if you want to support browsers that don’t handle scripting.

A scripting approach based on browser and version, is to trap the onLoad event for the browser page, and re-direct the Web page output to another page. You trap the onLoad event in the <BODY> tag, using the following code:

<BODY onLoad="change_document()">

The change_document function uses the navigator properties of appVersion and appName to find out which brower and version are being used to access the page. This is then used to create a string containing the URL of the re-directed output:

<SCRIPT Language="JavaScript">
<!--
   function change_document() {
      var MS=navigator.appVersion.indexOf("MSIE")
	var MSVER = parseInt(navigator.appVersion.substring(MS+5, MS+6))
    	var NSVER=parseInt(navigator.appVersion.substring(0,1))
	var locstring
	if (MS > 0) 
		locstring = "diffie" + MSVER + ".html"
    	else if (navigator.appName == "Netscape")
		locstring = "diffns" + NSVER + ".html"

	window.location = locstring
   }
//-->			
</SCRIPT>

To see an example of script re-direction, try this diff sample.

The downside to this type of browser and version difference handling is this: if you want to support Netscape Navigator 2.x, 3.x, 4.x, in addition to Internet Explorer 3.x and 4.x, you will need to create five pages for each Web “page” at your site!

However, this approach is effective if you wish to apply it selectively at your site. Perhaps you want to have an interactive product page that makes use of all the fun dynamic HTML techniques each browser is implementing. This approach could be used for this product page only, giving you the freedom to use the specific browser/version technology to its fullest.

Another technique to handling browser/version differences is to use scripting and style sheets in one page and ensure that the scripting is directed at the appropriate browser and version.

I will demonstrate this with the next sample code. The example will change the background color for all of the browsers and versions. This is all it will do for Netscape 2.x. For Internet Explorer 3.x, a CSS1 style will also re-define the appearance of the <H1> tag. For Netscape 3.x, the image that displays when the document first opens is changed. For IE 4.0, the image is changed and the style sheet definition for the <H1> tag also changes (both the font size and color). Finally, for Netscape 4.0, the <H1> tag is also changed, but this time using Dynamic Style Sheets (DSS), meaning that JavaScript has been applied to JavaScript Style Sheet (JSS) elements.

First, I apply some style sheet definitions for the Web page. A JavaScript style sheet and a standard CSS1 (Cascading Style Sheets) definition are created:

<STYLE TYPE="text/JavaScript">

	classes.class1.H1.fontSize="24pt";
	classes.class1.H1.color="green";

	classes.class2.H1.fontSize="18pt";
	classes.class2.H1.color="red";

</STYLE>
<STYLE TYPE="text/css">
	H1.newstyle { font-size: 18pt ; color: red }
		margin-top: -.05in ; margin-left: 1.0in } 
	H1 { font: 24pt ; color: green }

</STYLE>

These style sheet definitions provide for new formatting for the <H1> tag, and will be used in JavaScript functions that will be created a little later in this article.

Next, global variables will be defined that contain the type and version of the browser accessing this page. As these are global in nature, they will be available anywhere that JavaScript is used in the page:

<SCRIPT Language=JavaScript>
<!--
var MS=navigator.appVersion.indexOf("MSIE")
window.isIE4 = (MS>0) && 
    ((parseInt(navigator.appVersion.substring(MS+5,MS+6)) >= 4) &&  
    (navigator.appVersion.indexOf("MSIE"))>0)

var NSVER=parseInt(navigator.appVersion.substring(0,1))

isNS4 = false
isNS3 = false

if (navigator.appName == "Netscape") {
   if (NSVER == 3) {
	isNS3 = true
	}
   else if (NSVER >= 4) {
	isNS3 = true
	isNS4 = true
	}
   }

The next script is a function, change_doc, which will change the background color for the Web page for all versions of the browsers that access it. Additionally, if the browser is Netscape 3.x or 4.x, it calls another JavaScript function, change_document3:

function change_document() {
  	document.bgColor="beige"

    	if (isNS3) 
		change_document3()
	}

The next JavaScript function is change_new which is only called by IE 4.0. This function will apply the new style definition for the <H1> tag that has an id of “myheader”, using Microsoft’s own version of Dynamic HTML:

function change_new() {
	var chgh1 = document.all.myheader
    	chgh1.className = "newstyle"
	}
//--> 
</SCRIPT>

The scripting block is closed as the other functions will be creating in different versions of JavaScript. First, using JavaScript 1.1. we create the change_document3 function which will change the image shown in the  page. At the end of the function the value of the isNS3 is tested, and if true the function change_document4 is called. Note from the global variable section that isNS3 is set to true for both Netscape 3.x and Netscape 4.x:

<SCRIPT Language="JavaScript1.1"> 
<!--
function change_document3() {

    	if (!isNS4) 
	     document.thisimage.src="sun.gif"
    	else
	     change_document4()
	
	}
//-->
</SCRIPT>

Using the JavaScript 1.1 specification means that any script within this block will only be executed by a browser that is capable of processing JavaScript 1.1 script. This includes Netscape 3.x and 4.x, as well as IE 3.0x and 4.x.

The next function is change_document4, which is created in a JavaScript 1.2 scripting block. This function will be called only for Navigator 4.x. The script uses a <LAYER> tag to encapsulate the original contents of the page. When this function is called, those contents are hidden, and new contents are created using a new LAYER object:

<SCRIPT Language="Javascript1.2">
<!--
  function change_document4() {
	document.layers[0].visibility="hide"

	// note with following...another technique would be to 
	// create a second layer, set to invisibile, and use 
	// conditional comments to block for non-layer browsers...
	// not implemented, yet
	newlayer = new Layer(600)
	newlayer.visibility="inherit"
	newlayer.document.write("<img src='sun.gif' width=76 height=76 alt='sun'>")
	newlayer.document.write("<H1 class=class2> Header for this example page </H1>")
	newlayer.document.close()
	}
//-->
</SCRIPT>

I close the <HEAD> section. In the <BODY> tag, we trap the onLoad event for the Web page. This event will check to see if the browser and version is Internet Explorer 4.0. If it is, the change_newchange_document, and change_document3 functions are called. For the other browsers/versions, only the change_document function is called. Additionally, I create the image definition and <H1> contents:

<BODY 
onLoad="if (window.isIE4) {change_new(); change_document(); change_document3();} else change_document();">
<LAYER>
<img src="rain.gif" width=76 height=76 alt="rain" name="thisimage">
<H1 id=myheader> Header for this example page </H1>
</LAYER>

Let’s take a look at this sample page in action.

This approach is just one of many that could be taken to determine the browser and version, and only execute the appropriate scripting. Different scripting blocks were used for the different versions of Navigator as there will usually be other functions and event handlers that will be coded and that are only implemented with the specific version. As an example, a new object for Navigator 3.x was the IMAGE object, for Navigator 4.x, it is the LAYER tag. Enclosing the code in these scripting specific versions ensures that a browser that is not capable of processing the object does not process the code.

One nice feature that Netscape implemented in Navigator 3.x, and I hope it continues to implement with version 4, is the ability to provide overloading of functions based on versions of JavaScript. As an example, I created this test page that splits the functionality completely by JavaScript version. Each version has a function called change_document(). Navigator 2.x and Internet Explorer 3.x will access and execute the script it finds in the topmost “JavaScript” block. Navigator 3.x will go for the section with the <SCRIPT LANGUAGE="JavaScript1.1"> tag.

As I write these words, Navigator 4.0 does not go for the section for JavaScript 1.2, but I will continue to test for this functionality and hope to see this in a future preview release, or the final release. IE 4.0 does execute the script in the JavaScript 1.2 section. Add in a little use of navigator.appName and you can duplicate the functionality created earlier by having the browser execute the right script by default.

Unfortunately, Microsoft does not seem to support the concept of versions with the use of VBScript (if it does, please let me know).

Browser-friendly Web page rulesHere are some good rules of thumb I use when creating browser-friendly Web sites.

1. Know your audience
Most of the people that visit my site are Web page developers, and I can alter and play with the contents knowing that most people viewing my site will be using the newest browsers, and most likely are using Navigator and Internet Explorer. If your Web site is for a bank, or a book company, or other non-computing related company, you may not want to use too much new technology.
2. Make a decision on browser support
After stating rule 1, I will now extend it by saying that you can’t please all the people all the time. You will want to make a decision as to whether the cost of providing support for a specific browser is worth the possible loss of visitors to your site.
3. Integrate new technology unobtrusively
If you create one page for multiple browser/versions, make sure you use technology carefully, and in such a way as to not take from the overall style and meaning of the page. With the example shown in the last section, the page dynamically changes based on the browser, but the overall content (what there is of it) is not changed. Reserve your wilder instincts for special fun pages and then implement the first technique given in this article to load browser specific pages.
4. Always provide at least one text based page for your site, if not for each Web page
On pages where navigation is crucial, make sure you offer text-only links for users of obscure or non-graphical browsers, such as Lynx. Again, though, balance this with your known audience.
5. Be aware of those with special physical challenges
Do not use image maps without providing a text-based menu. Always provide an ALT property for any images you use. Do not rely on the newer technologies as the only method for communicating an idea, a product, a service, or for site navigation.
6. Test your Web pages with your target browsers and versions
Once you decide which browsers and versions you are supporting, always test your Web pages with all of them. This may mean you have to use multiple machines, or a system with dual-booting operating systems.
7. Have fun
If you find yourself becoming incredibly frustrated with trying to get something that works easily with one browser or version, to work with another, you might want to stop, walk away, take a break and then try approaching your scripting challenge from a different perspective. If something will not work, then find what does work and find a way to apply it to your current problem.

Happy scripting!

 

Categories
Technology

A Simple Solution to the Complex Distribution Problem

Recovered from the Wayback Machine.

Any information system group that has a client base that is split geographically will have a problem with distribution: how do you notify the clients that a new version of the tool(s) they are using is out, what the version contains, and how to upgrade.

You can automate the upgrade process by using tools that determine that the application a person is accessing is now out of date and upgrading it accordingly. The problem with this approach is that the user will not have control of when the upgrade is occurring and may be wary of an update that they know nothing about.

You can take a more passive approach by sending an email or memo out to all of your clients that an update has occurred to the application and they then can access the update on a certain sub-directory. The problem with this is that unless the update is fixing a problem that the client specifically wants or asked for, they may not be as willing to take the time to make the upgrade to their own installation, and then you in the IS department are now faced with trying to support multiple installations using multiple versions of your product. Additionally, the application user will then have to find this upgrade, download it on their own, and install the upgrade, a multiple step process which can generate problems.

Is there a simple solution? There is a simple possibility.

Many companies are interested in porting applications to the Web in some form of an internal intranet just for this problem. Unfortunately as many IS departments are finding out, most applications will not port to the web that easily. However, this is not the only way the web can be used to solve migration and upgrade problems.

Another approach is to use techniques such as Server Side Includes and to use the concept of the personalized user page. This is a web document that the user will open every morning. The contents of the document have been personalized for the user and presents information from categories that they have chosen. A case in point is that a person who works with Group A in Department 1B for Division J for Company XYZ. They will have a web page that contains new information pertinent to Company XYZ at the top, then information pertinent only to Division J next, information for Department 1B next, and finally information for Group A.

A Server Side Include (SSI) embeds a command line in the HTML document given an extension which is usually .shtml or .stm (the webmaster can determine what this extension is). This type of extension tells the web server to parse the web document for SSI commands before sending the document to the browser. An example of one of these commands is:

<!–#include file=”company.html” –>

This SSI command will instruct the web server to open the file called company.html and load the contents of company.html at this point.

The advantage of this approach should be fairly obvious: the information is specific to the interests and needs of the individual and is presented in such a way that they can examine it for the entire day if they need to; the information can include links to other documents if the person wishes to pursue more in-depth knowledge; and the document can be saved using most browers SaveAs capability. In stead of a flurry of emails which may or may not contain information that is relevant and that can be ignored and difficult to follow or read you have one document that contains all the information.

Another advantage is that no programming is required, and the information for each department can be maintained by each department. Group A maintains the HTML document that is specific to them. If there is no new information a blank HTML document or one containing the words “No New Information” can be given. Division J can maintain their own HTML document, and so on. With the many many simple to use HTML tools this should not be a solution that requires programming intervention.

While presenting a unified approach to information presentation, each group maintains autonomous control over what information is presented.

For our distribution problem, if IS has upgraded software that is in use throughout Division J, a notice can go into the Division J section that a new version of the software is being created, what bugs it will fix and features it will add. When the software is ready, a link can be inserted into the document that will allow the person to download the upgrade with one click of the button. The user can then double click on this file as soon as it is on their machine and the upgrade process can occur.

What is the advantage of this technique over others? The information about the upgrade is presented in the same format and in the same context as the upgrade itself. Information about the upgrade and the upgrade itself are only given to those who are impacted by it.

How can this solve the multiple version problem? After all the user can continue to ignore the upgrade notice and continue on their merry way. Well, this is where the concept of something called a Netscape Cookie comes in.

A Netscape cookie, implemented by both Netscape and Internet Explorer browsers, is a tiny bit of information that is stored locally on the client’s machine and that can be accessed by the browser when a specific web document is loaded. When the document containing the information about the upgrade is loaded, this value is set for the first time. After that point every time the person accesses their personalized web page the cookie is accessed and the value is incremented or decremented. Information can be printed out to the effect that they have so many days to make the upgrade, and this value is decremented for each day.

If they make the upgrade, the cookie information is destroyed and the reader will no longer get the count down.

With additional sophistication, one can create the page in such a way that the download no longer shows once they make the upgrade. To use this approach, persisten information about what HTML documents one specific person will see is kept in a file on the server. When the person logs in and gives their user name and password this file is accessed. Instead of an HTML document the person accesses a file that is called index.cgi. This application will access the file containing the person’s preferences and the information is then used to determine how to build the page the person will see. The application does this by opening up the individual HTML documents that make up the person’s preferences and printing them back to the browser, in turn.

With this approach, after a person makes an upgrade their personal preference file is accessed and the entry that contains the upgrade information is removed. Not only will the person receive timely information that is pertinent to their needs, they will receive content that is dynamic and also matches their choices.

Finally, if the person still does not upgrade by a specific date an email can be generated automatically that will be sent to the IS department informing them of this information.

A link file containing sample Perl script that demonstrates the CGI based approach and that demonstrates the use of SSI can be found here.