Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

Essential JavaScript

This chapter is from the book

This chapter is from the book

Handling Cross-Browser Programming Issues

Nothing's more annoying than working hard on a script that performs beautifully when you test it, only to get email from users telling you that your script doesn't work at all—and that you should test your JavaScript before embedding it in web pages. With so many browser types, and so many browser versions, it's very hard to get any but the most rudimentary scripts to run for all users unless you pay attention to cross-browser compatibility issues.

The biggest such issue is what properties, methods, and events are supported by what browser objects, and I'll start by taking a look at that issue here.

Cross-Browser Issues: Differing Object Models

Unlike other books, this book is designed to make dealing with cross-browser object models easy—or at least easier. When there's an incompatibility, I'll point it out. For each property, method, and event of the various browser objects, I'm going to list which browser, and which version of which browser, supports them.

That information will give you what you need to deal with nearly all cross-browser issues. You don't have to worry about what will work in what browser—you'll be able to look it up directly in the reference material for the properties, methods, and events of the various objects. For example, you can quickly see all the browser versions that support the reset method in the sample entry in Table 1.1—here, NS2 stands for Netscape Navigator 2.0, IE5 stands for Internet Explorer 5.0, and so on. (I'll present all objects' properties, methods, and events this way—as well as all the syntax of the JavaScript language itself—enabling you to deal with cross-browser issues easily.)

Table 1.1 Sample Object Method Entry

Method

NS2

NS3

NS4

NS6

IE3a

IE3b

IE4

IE5

IE5.5

IE6

reset

 

x

x

x

x

x

x

x

Returns: Nothing


This method simulates clicking the Reset button in a form, which resets the data in the form's controls back to their default values (which you can set with most controls' VALUE attribute). This method causes the onreset event to occur. Syntax: form.reset().

Note in particular the two entries for Internet Explorer versions 3a and 3b in Table 1.1; two different Internet Explorer versions 3.0 were released, and I'll label them 3a and 3b. You can tell the difference between these browsers with object detection—detecting the existence of objects on-the-fly—as discussed in Chapter 4.

Cross-Browser Issues: Built-in JavaScript Objects

Besides the browser objects that you work with in most JavaScript scripts, JavaScript itself has some built-in objects that deserve mention, and a few chapters in this book are devoted to them. The available objects differ to some degree between JavaScript and JScript. In particular, here are the built-in objects in JavaScript 1.5 and what they do:

  • Array. Supports creation of arrays.

  • Boolean. Supports Boolean values (which can hold only values of True or False).

  • Date. Supports working with dates and times.

  • Function. Specifies a string of JavaScript code to be compiled as a function.

  • Math. Support for many math routines, such as square root.

  • Number. Supports numeric data types.

  • Object. Provides functionality common to all JavaScript objects.

  • RegExp. Supports regular expression string matching.

  • String. Supports manipulation of text strings.

And here are the built-in language objects in JScript 5.6:

  • ActiveXObject. Supports Internet Explorer ActiveX objects.

  • Array. Supports creation of arrays.

  • Boolean. Supports Boolean values (which can hold only values of True or False).

  • Date. Supports working with dates and times.

  • Dictionary. Supports storing key/value data item pairs.

  • Enumerator. Supports working with collections of objects.

  • Error. Contains information about the errors that have occurred in a script.

  • FileSystemObject. Gives you some access to the computer's file system.

  • Function. Specifies a string of JavaScript code to be compiled as a function.

  • Global. Collects various methods available anywhere in a script together into one object.

  • Math. Support for many math routines, such as square root.

  • Number. Supports numeric data types.

  • Object. Provides functionality common to all JavaScript objects.

  • RegExp. Supports regular expression string matching.

  • String. Supports manipulation of text strings.

  • VBArray. Gives you access to Microsoft Visual Basic safe arrays in the Internet Explorer.

When covering the properties, methods, and events of these objects, I'll indicate which browsers, and what versions of those browsers (just as with the browser objects).

Cross-Browser Issues: Core Language and Language Version

One area where some compatibility has finally appeared is in the core JavaScript language itself. Both the JavaScript language in the Netscape Navigator and the JScript language in the Internet Explorer are now compliant with the ECMA standard ECMAScript version 3. That means when it comes to the core language itself, which we'll be learning in the next two chapters, you usually don't have to worry about incompatibilities if you're dealing with recent browsers.

The JavaScript language itself is made up of various keywords, and we'll become familiar with these keywords in the next two chapters, which are on the syntax of JavaScript. These keywords are called reserved words in JavaScript, because they are already part of the JavaScript language and may not be used for any other purpose. For reference, you'll find the reserved words in JavaScript 1.5 in Table 1.2, and the reserved words in JScript 5.6 in Table 1.3. JScript 5.6 also reserves some words for possible future use, and you'll find them in Table 1.4.

Table 1.2 Netscape's JavaScript 1.5 Reserved Words

abstract

boolean

break

byte

case

catch

char

class

const

continue

debugger

default

delete

do

double

else

enum

export

extends

false

final

finally

float

for

function

goto

if

implements

import

in

instanceof

int

interface

long

native

new

null

package

private

protected

public

return

short

static

super

switch

synchronized

this

throw

throws

transient

true

try

typeof

var

void

volatile

while

with

 


Table 1.3 Microsoft's JScript 5.6 Reserved Words

break

delete

function

return

typeof

case

do

if

switch

var

catch

else

in

this

void

continue

false

instanceof

throw

while

debugger

finally

new

true

with

default

for

null

try


Table 1.4 Microsoft's JScript 5.6 Future Reserved Words

abstract

double

goto

native

static

boolean

enum

implements

package

super

byte

export

import

private

synchronized

char

extends

int

protected

throws

class

final

interface

public

transient

const

float

long

short

volatile


Despite the recent compliance with the ECMA version 3 standard, however, earlier versions of the browsers support different versions of JavaScript, and that introduces incompatibilities.

That means it's often important to know what version of JavaScript you're working with; so I'll put that information into a set of tables here. You'll find the JavaScript version listed by Netscape Navigator version in Table 1.5, and the JScript version (as well as which JavaScript version each JScript version matched) listed by Internet Explorer version in Table 1.6. Note that Internet Explorer 3.0 actually had two releases, which I'll call 3a and 3b throughout the book, which supported JavaScript 1.0 and 1.1 respectively.

Table 1.5 Netscape Navigator JavaScript Version by Browser Version

JavaScript Version

Netscape Navigator Version

1.0

2.0

1.1

3.0

1.2

4.0 to 4.05

1.3

4.06 to 4.7

1.4

Not implemented

1.5

6.0 (ECMA 3 compliant)


Table 1.6 Internet Explorer JScript Version by Browser Version

JScript Version

JavaScript Version

Internet Explorer Version

1.0

1.0

3a

2.0

1.1

3b

3.0

1.2

4.0

4.0

Not implemented

Not implemented

5.0

1.3

5.0

5.5

1.5

5.5 (partly ECMA 3 compliant)

5.6

1.5

6.0 (ECMA 3 compliant)


In fact, to further complicate the version issue, Netscape is already hard at work on JavaScript 2.0, now in the planning stages. You can find information about this version of JavaScript as it's being designed at http://www.mozilla.org/js/language/js20/introduction/index.html.

How will JavaScript 2.0 differ from JavaScript 1.5? Here's the current list of additions in JavaScript 2.0 as it appears on the JavaScript 2.0 site—these items are quoted from that site. (Note that these items will make sense only if you've already programmed in JavaScript and have some object-oriented programming experience.)

  • Class definition syntax, both static and dynamic

  • Packages, including a versioning mechanism

  • Types for program and interface documentation

  • Invariant declarations such as const and final

  • Private, internal, public, and user-defined access controls

  • Introspection facilities

  • Overridable basic operators, such as + and [ ]

  • Machine types, such as int32, for more faithful communication with other programming languages

With all these compatibility issues going on, it is often important to know which browser and version you're using. So how do you know? I'll take a look at that now.

Cross-Browser Issues: Which Browser Are You Using?

We'll deal in depth with cross-browser programming throughout the book, especially in Chapter 4, and an important part of that is knowing what browser version your script is executing in. That's where the navigator browser object comes in; this object is another of the browser objects you work with in JavaScript. Here are the relevant properties of this object:

  • navigator.AppName. The name of the browser application.

  • navigator.AppVersion. The version of the browser.

  • navigator.UserAgent. More details about the browser.

The following script displays these properties in a web page:

(Listing 01-07.html on the web site)

<HTML>
  <HEAD>
    <TITLE>
      Checking Your Browser Type
    </TITLE>
  </HEAD>

  <BODY>
    <SCRIPT LANGUAGE="JavaScript">
      document.write("navigator.appName: " + navigator.appName) 
      document.write("<BR><BR>")
      document.write("navigator.appVersion: " + navigator.appVersion) 
      document.write("<BR><BR>")
      document.write("navigator.userAgent: " + navigator.userAgent) 
    </SCRIPT>

    <H1>Checking Your Browser Type</H1>
  </BODY>
</HTML>

The + operators in this code are used to join text strings together, as we'll see in the next chapter. (Here, I'm joining the text "navigator.appName: " to the actual value of navigator.appName, and so on for navigator.appVersion and navigator.userAgent.) You can see the results of this script in the Internet Explorer in Figure 1.12, and in the Netscape Navigator in Figure 1.13. Note the appVersion property does not give you what you might expect—I'm using Internet Explorer 6.02, but appVersion is reported as 4.0, and I'm also using Netscape Navigator 6.2, but appVersion is reported as 5.0. To find the true browser version, you must search the userAgent text—you can see the text "MSIE 6.0" for Internet Explorer and "Netscape6/6.2" for Netscape Navigator in these two figures, which give the correct version.

Figure 1.12 Getting browser information in the Internet Explorer.

Figure 1.13 Getting browser information in the Netscape Navigator.

Why do both userAgent property values begin with "Mozilla" (as seen in these figures)? Mozilla is Netscape's free development browser that is a developer community effort to test new innovations in web browsing. In the early days of JavaScript, many scripts would search the userAgent property for the word Mozilla to determine whether the browser supported JavaScript, and that's why that property still begins with "Mozilla".

Tip

The Mozilla browser is available at http://www.mozilla.org for free; it's a cutting edge browser that implements the various ECMA and W3C standards for JavaScript, but it's not in widespread use compared to the two main browsers available.

Checking the properties of the navigator object is one way to see what type of browser you're working with, and we'll work with this technique in Chapter 4. However, even the same version of a browser can have different capabilities on different platforms (such as Windows or the Mac). A better technique, as we'll see in Chapter 4, is to use direct object detection, which enables you to check for the existence of a browser object before you try to use it in your script. More on this in Chapter 4.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020