Jump to content

User:Moncur/01

Ka Wiktionary

1 Understanding JavaScript

[wax ka badal]

The World Wide Web (WWW) began as a text-only medium, the first browsers didn't even support images within web pages. Although it's still not quite ready to give television a run for its money, the Web has come a long way since then.

Today's websites can include a wealth of features: graphics, sounds, animation, video, and occasionally useful content. Web scripting languages, such as JavaScript, are one of the easiest ways to spice up a web page and to interact with users in new ways.

The first hour of this book introduces the concept of web scripting and the JavaScript language. It also describes how JavaScript fits in with other web languages.

Learning Web Scripting Basics

[wax ka badal]

In the world of science fiction movies (and many other movies that have no excuse), computers are often seen obeying commands in English. Although this might indeed happen in the near future, computers currently find it easier to understand languages such as BASIC, C, and Java.

If you know how to use HTML (Hypertext Markup Language) to create a web document, you've already worked with one computer language. You use HTML tags to describe how you want your document formatted, and the browser obeys your commands and shows the formatted document to the user.

Because HTML is a simple text markup language, it can't respond to the user, make decisions, or automate repetitive tasks. Interactive tasks such as these require a more sophisticated language: a programming language, or a scripting language.

Although many programming languages are complex, scripting languages are generally simple. They have a simple syntax, can perform tasks with a minimum of commands, and are easy to learn. Web scripting languages enable you to combine scripting with HTML to create interactive web pages.

Scripts and Programs

[wax ka badal]

A movie or a play follows a script, a list of actions (or lines) for the actors to perform. A web script provides the same type of instructions for the web browser. A script in JavaScript can range from a single line to a full-scale application. (In either case, JavaScript scripts usually run within a browser.)

By the Way
Is JavaScript a scripting language or a programming language? It depends on who you ask. We'll refer to scripting throughout this book, but feel free to include JavaScript programming on your résumé after you've finished this book.

Some programming languages must be compiled, or translated, into machine code before they can be executed. JavaScript, on the other hand, is an interpreted language: The browser executes each line of script as it comes to it.

There is one main advantage to interpreted languages: Writing or changing a script is very simple. Changing a JavaScript script is as easy as changing a typical HTML document, and the change is enacted as soon as you reload the document in the browser.

By the Way
Interpreted languages have their disadvantages. They can't execute really quickly, so they're not ideally suited for complicated work, such as graphics. Also, they require the interpreter (in JavaScript's case, usually a browser) in order to work.

Introducing JavaScript

[wax ka badal]

JavaScript was developed by Netscape Communications Corporation, the maker of the Netscape web browser. JavaScript was the first web scripting language to be supported by browsers, and it is still by far the most popular.

By the Way
A bit of history: JavaScript was originally called LiveScript and was first introduced in Netscape Navigator 2.0 in 1995. It was soon renamed JavaScript to indicate a marketing relationship with Sun's Java language.

JavaScript is almost as easy to learn as HTML, and it can be included directly in HTML documents. Here are a few of the things you can do with JavaScript:

  • Display messages to the user as part of a web page, in the browser's status line, or in alert boxes
  • Validate the contents of a form and make calculations (for example, an order form can automatically display a running total as you enter item quantities)
  • Animate images or create images that change when you move the mouse over them
  • Create ad banners that interact with the user, rather than simply displaying a graphic
  • Detect the browser in use or its features and perform advanced functions only on browsers that support them
  • Detect installed plug-ins and notify the user if a plug-in is required
  • Modify all or part of a web page without requiring the user to reload it
  • Display or interact with data retrieved from a remote server

You can do all this and more with JavaScript, including creating entire applications. We'll explore the uses of JavaScript throughout this book.

How JavaScript Fits into a Web Page

[wax ka badal]

As you hopefully already know, HTML is the language you use to create web documents. To refresh your memory, Listing 1.1 shows a short but sadly typical web document.

Listing 1.1. A Simple HTML Document
<html>
<head>
<title>Our Home Page</title>
</head>
<body>
<h1>The American Eggplant Society</h1>
<p>Welcome to our Web page. Unfortunately,
it's still under construction.</p>
</body>
</html>

This document consists of a header within the <head> tags and the body of the page within the <body> tags. To add JavaScript to a page, you'll use a similar tag: <script>.

The <script> tag tells the browser to start treating the text as a script, and the closing </script> tag tells the browser to return to HTML mode. In most cases, you can't use JavaScript statements in an HTML document except within <script> tags. The exception is event handlers, described later in this hour.

JavaScript and HTML

Using the <script> tag, you can add a short script (in this case, just one line) to a web document, as shown in Listing 1.2.

Did you Know?
If you want to try this example in a browser but don't want to type it, the HTML document is available on this book's website (as are all of the other listings).
Listing 1.2. A Simple HTML Document with a Simple Script

<html>
<head>
<title>Our Home Page</title>
</head>
<body>
<h1>The American Eggplant Society</h1>
<p>Welcome to our Web page. Unfortunately,
it's still under construction.
We last worked on it on this date:
<script language="JavaScript" type="text/javascript">
document.write(document.lastModified);
</script>
</p>
</body>
</html>

JavaScript's document.write statement, which you'll learn more about later, sends output as part of the web document. In this case, it displays the modification date of the document.

By the Way
Notice that the <script> tag in Listing 1.2 includes the parameter type="text/javascript". This specifies the scripting language to the browser. You can also specify a JavaScript version, as you'll learn later in this hour.

In this example, we placed the script within the body of the HTML document. There are actually four different places where you might use scripts:

  • In the body of the page In this case, the script's output is displayed as part of the HTML document when the browser loads the page.
  • In the header of the page between the <head> tags Scripts in the header don't immediately affect the HTML document, but can be referred to by other scripts. The header is often used for functionsgroups of JavaScript statements that can be used as a single unit. You will learn more about functions in Hour 3, "Getting Started with JavaScript Programming."
  • Within an HTML tag, such as <body> or <form> This is called an event handler and enables the script to work with HTML elements. When using JavaScript in event handlers, you don't need to use the <script> tag. You'll learn more about event handlers in Hour 3.
  • In a separate file entirely JavaScript supports the use of files with the .js extension containing scripts; these can be included by specifying a file in the <script> tag.
Using Separate JavaScript Files

When you create more complicated scripts, you'll quickly find your HTML documents become large and confusing. To avoid this, you can use one or more external JavaScript files. These are files with the .js extension that contain JavaScript statements.

External scripts are supported by all modern browsers. To use an external script, you specify its filename in the <script> tag:

<script language="JavaScript" type="text/javascript" src="filename.js">
</script>

Because you'll be placing the JavaScript statements in a separate file, you don't need anything between the opening and closing <script> tags, in fact, anything between them will be ignored by the browser.

You can create the .js file using a text editor. It should contain one or more JavaScript commands, and only JavaScriptdon't include <script> tags, other HTML tags, or HTML comments. Save the .js file in the same directory as the HTML documents that refer to it. See the Try It Yourself section of Hour 2 for an example of separate HTML and script files.

Did you Know?
External JavaScript files have a distinct advantage: You can link to the same .js file from two or more HTML documents. Because the browser stores this file in its cache, this can reduce the time it takes your web pages to display.

Events

[wax ka badal]

Many of the useful things you can do with JavaScript involve interacting with the user, and that means responding to events, for example, a link or a button being clicked. You can define event handlers within HTML tags to tell the browser how to respond to an event. For example, Listing 1.3 defines a button that displays a message when clicked.

Listing 1.3. A Simple Event Handler

<html>
<head>
<title>Event Test</title>
</head>
<body>
<h1>Event Test</h1>
<button onclick="alert('You clicked the button.')">
</body>
</html>

In Hour 9, "Responding to Events," you'll learn more about JavaScript's event model and creating simple and complex event handlers.

By the Way
You can also use an external script to define event handlers. This is a good practice because it lets you keep all of your JavaScript in one place, rather than scattered across the HTML document. See Hour 9 for details.

Browsers and JavaScript

[wax ka badal]

Like HTML, JavaScript requires a web browser to be displayed, and different browsers may display it differently. Unlike HTML, the results of a browser incompatibility with JavaScript are more drastic: Rather than simply displaying your text incorrectly, the script may not execute at all, may display an error message, or may even crash the browser.

We'll take a quick look at the way different browsers and different versions of the same browser treat JavaScript in the following sections.

The DOM (Document Object Model)

[wax ka badal]

Let's start with one reason you shouldn't have to think too much about different browsers. Almost everything you do with JavaScript involves working with the Document Object Model (DOM), a standardized set of objects that represent a web document.

The DOM includes objects that enable you to work with all aspects of the current document. For example, you can read the value the user types in a form field, or the filename of the current page.

The DOM is defined by the W3C (World Wide Web Consortium) and the latest browsers support DOM levels 1 and 2, which enable you to control all parts of a web page with JavaScript.

Did you Know?
Early versions of the DOM only allowed JavaScript to manipulate certain parts of a page, such as form elements and links. The new DOM enables you to work with every element defined in HTML.

Internet Explorer

[wax ka badal]

Microsoft's Internet Explorer (IE) browser was a latecomer to the Internet, but has now become the most popular browser. The latest versions of IE support most of JavaScript 1.5 and the W3C DOM.

At this writing, IE 6.0 is the latest released version, and IE 7.0 is in beta. Although most of the examples in this book will work in IE 5.0 and later, I recommend testing your scripts with the latest browsers.

Netscape and Firefox

[wax ka badal]

Netscape, which for a time made the Web's most popular browser, established the Mozilla Foundation to maintain an open-source version of the browser. This led to the Mozilla browser and more recently, Firefox, a streamlined browser based on the Mozilla engine.

Firefox has recently begun to challenge Microsoft's browser dominance, with an estimated 10% of web users. That might not sound like many, but ignoring Firefox means ignoring at least 10% of your audience, and on many sites the percentage is much higher.

Firefox is available for Windows, Macintosh, and Linux platforms and is free, open-source software. You can download Firefox from the Mozilla website at http: //www.mozilla.org/ .

At this writing, the current version of Firefox is 1.5. Most of the scripts in this book will work with Firefox 1.0 or later, as well as versions 6 and 7 of the Netscape browser.

By the Way
Netscape 4.0 and Internet Explorer 4.0 supported incompatible versions of Dynamic HTML (DHTML)an attempt to overcome the limits of the current DOM. The new W3C DOM eliminates the need for these proprietary models, and you can now write standard code that will work on most modern browsers.

Other Browsers

[wax ka badal]

Although Internet Explorer and Firefox are the most popular browsers, there are many other browsers. Here are two less-common browsers you'll probably hear about:

  • Safari, Apple's browser, is included with MacOS and is the default browser on most Macintosh computers.
  • Opera, from Opera Software, is an alternative browser notable for its support of many platforms, including mobile phones. The latest version of Opera, 8.0, supports the W3C DOM and JavaScript 1.5, and should work with most scripts in this book.
Did you Know?
There are many other browsers out there, but you don't need to know all of them to create working scripts, as long as you follow the standards, your scripts will work on browsers that support JavaScript almost every time. This book will focus on teaching standards-based scripting that will work in all modern browsers.

Versions of JavaScript

[wax ka badal]

The JavaScript language has evolved since its original release in Netscape 2.0. There have been several versions of JavaScript:

  • JavaScript 1.0, the original version, is supported by Netscape 2.0 and Internet Explorer 3.0.
  • JavaScript 1.1 is supported by Netscape 3.0 and mostly supported by Internet Explorer 4.0.
  • JavaScript 1.2 is supported by Netscape 4.0 and partially supported by Internet Explorer 4.0.
  • JavaScript 1.3 is supported by Netscape 4.5 and Internet Explorer 5.0 and 6.0.
  • JavaScript 1.5 is partially supported by Internet Explorer 6.0, and supported by Netscape 6.0 and Firefox 1.0.
  • JavaScript 1.6 is currently supported by Firefox 1.5.

Each of these versions is an improvement over the previous version and includes a number of new features. With rare exception, browsers that support the new version will also support scripts written for earlier versions.

The European Computer Manufacturing Association (ECMA) has finalized the ECMA-262 specification for ECMAScript, a standardized version of JavaScript. JavaScript 1.3 follows the ECMA-262 standard, and JavaScript 1.5 follows ECMA-262 revision 3.

By the Way
Another language you might hear of is JScript. This is how Microsoft refers to its implementation of JavaScript, which is generally compatible with the standard version.

The Mozilla Foundation, the open-source offshoot of Netscape that develops the Firefox browser, is also working with ECMA on JavaScript 2.0, a future version that will correspond with the fourth edition of the ECMAScript standard. JavaScript 2.0 will improve upon earlier versions with a more modular approach, better object support, and features to make JavaScript useful as a general-purpose scripting language as well as a web language.


Specifying JavaScript Versions

[wax ka badal]

As mentioned earlier in this hour, you can specify a version of JavaScript in the <script> tag. For example, this tag specifies JavaScript version 1.3:

<script language="JavaScript1.3" type="text/javascript">

There are two ways of specifying the JavaScript language in the <script> tag. The old method uses the language attribute, and the new method recommended by the HTML 4.0 specification uses the type attribute. To maintain compatibility with older browsers, you can use both attributes.

When you specify a version number in the language attribute, this allows your script to execute only if the browser supports the version you specified or a later version.

When the <script> tag doesn't specify a version number, all browsers that support JavaScript will run the script. Because most of the JavaScript language has remained the same since version 1.0, you will rarely need to worry about JavaScript versions.

Did you Know?
In most cases, you shouldn't specify a JavaScript version at all. This allows your script to run on all of the browsers that support JavaScript. You should only specify a particular version when your script uses features unique to a specific version.

JavaScript Beyond the Browser

[wax ka badal]

Although JavaScript programs traditionally run within a web browser, and web-based JavaScript is the focus of this book, JavaScript is becoming increasingly popular in other applications. Here are a few examples:

  • Adobe Dreamweaver and Flash, used for web applications and multimedia, can be extended with JavaScript.
  • Several server-side versions of JavaScript are available. These run within a web server rather than a browser.
  • Microsoft's Windows Scripting Host (WSH) supports JScript, Microsoft's implementation of JavaScript, as a general-purpose scripting language for Windows. Unfortunately, the most popular applications developed for WSH so far have been email viruses.
  • Microsoft's Common Language Runtime (CLR), part of the .NET framework, supports JavaScript.

Along with these examples, many of the changes in the upcoming JavaScript 2.0 are designed to make it more suitable as a general-purpose scripting language.

Exploring JavaScript's Capabilities

[wax ka badal]

If you've spent any time browsing the Web, you've undoubtedly seen lots of examples of JavaScript in action. Here are some brief descriptions of typical applications for JavaScript, all of which you'll explore further, later in this book.

Improving Navigation

[wax ka badal]

Some of the most common uses of JavaScript are in navigation systems for websites. You can use JavaScript to create a navigation tool, for example, a drop-down menu to select the next page to read, or a submenu that pops up when you hover over a navigation link.

When it's done right, this kind of JavaScript interactivity can make a site easier to use, while remaining usable for browsers that don't support JavaScript.

Validating Forms

[wax ka badal]

Form validation is another common use of JavaScript. A simple script can read values the user types into a form and make sure they're in the right format, such as with ZIP Codes or phone numbers. This allows users to notice common errors and fix them without waiting for a response from the web server. You'll learn how to write form validation scripts in Hour 11, "Getting Data with Forms."

Special Effects

[wax ka badal]

One of the earliest and most annoying uses of JavaScript was to create attention-getting special effectsfor example, scrolling a message in the browser's status line or flashing the background color of a page.

These techniques have fortunately fallen out of style, but thanks to the W3C DOM and the latest browsers, some more impressive effects are possible with JavaScript, for example, creating objects that can be dragged and dropped on a page, or creating fading transitions between images in a slideshow.

Remote Scripting (AJAX)

[wax ka badal]

For a long time, the biggest limitation of JavaScript was that there was no way for it to communicate with a web server. For example, you could use it to verify that a phone number had the right number of digits, but not to look up the user's location in a database based on the number.

Now that some of JavaScript's advanced features are supported by most browsers, this is no longer the case. Your scripts can get data from a server without loading a page, or send data back to be saved. These features are collectively known as AJAX (Asynchronous JavaScript And XML), or remote scripting. You'll learn how to develop AJAX scripts in Hour 17, "AJAX: Remote Scripting."

You've seen AJAX in action if you've used Google's Gmail mail application, or recent versions of Yahoo! Mail or Microsoft Hotmail. All of these use remote scripting to present you with a responsive user interface that works with a server in the background.

Alternatives to JavaScript

[wax ka badal]

JavaScript is not the only language used on the Web, and in some cases, it may not be the right tool for the job. Other languages, such as Java, can do some things better than JavaScript. In the following sections, we'll look at a few other commonly used web languages and their advantages.

Java is a programming language developed by Sun Microsystems that can be used to create applets, or programs that execute within a web page.

Java is a compiled language, but the compiler produces code for a virtual machine rather than a real computer. The virtual machine is a set of rules for bytecodes and their meanings, with capabilities that fit well into the scope of a web browser.

The virtual machine code is then interpreted by a web browser. This allows the same Java applet to execute the same way on PCs, Macintoshes, and UNIX machines, and on different browsers.

By the Way
Java is also a densely populated island in Indonesia and a slang term for coffee. This has resulted in a widespread invasion of coffee-related terms in computer literature.

At this point, we need to make one thing clear: Java is a fine language, but you won't be learning it in this book. Although their names and some of their commands are similar, JavaScript and Java are entirely different languages.

ActiveX

[wax ka badal]

ActiveX is a specification developed by Microsoft that enables ordinary Windows programs to be run within a web page. ActiveX programs can be written in languages such as Visual C++ and Visual Basic, and they are compiled before being placed on the web server.

ActiveX applications, called controls, are downloaded and executed by the web browser, like Java applets. Unlike Java applets, controls can be installed permanently when they are downloaded, eliminating the need to download them again.

ActiveX's main advantage is that it can do just about anything. This can also be a disadvantage: Several enterprising programmers have already used ActiveX to bring exciting new capabilities to web pages, such as "the web page that turns off your computer" and "the web page that formats your disk drive."

Fortunately, ActiveX includes a signature feature that identifies the source of the control and prevents controls from being modified. Although this won't prevent a control from damaging your system, you can specify which sources of controls you trust.

ActiveX has two main disadvantages: First, it isn't as easy to program as a scripting language or Java. Second, ActiveX is proprietary, it works only in Microsoft Internet Explorer, and only under Windows platforms.

VBScript

[wax ka badal]

VBScript, sometimes known as Visual Basic Scripting Edition, is Microsoft's answer to JavaScript. Just as JavaScript's syntax is loosely based on Java, VBScript's syntax is loosely based on Microsoft Visual Basic, a popular programming language for Windows machines.

Like JavaScript, VBScript is a simple scripting language, and you can include VBScript statements within an HTML document. VBScript can work with the DOM in the same way as JavaScript. To begin a VBScript script, you use the <script LANGUAGE="VBScript"> tag.

VBScript can do many of the same things as JavaScript, and it even looks similar in some cases. It has two main advantages:

  • For those who already know Visual Basic, it may be easier to learn than JavaScript.
  • It is closely integrated with ActiveX, Microsoft's standard for web-embedded applications.

VBScript's main disadvantage is that it is supported only by Microsoft Internet Explorer. JavaScript, on the other hand, is supported by Netscape, Internet Explorer, and several other browsers. JavaScript is a much more popular language, and you can see it in use all over the Web.

CGI and Server-Side Scripting

[wax ka badal]

CGI (Common Gateway Interface) is not really a language, but a specification that enables programs to run on web servers. CGI programs can be written in any number of languages, including Perl, C, and Visual Basic.

Along with traditional CGI, scripting languages such as Microsoft's Active Server Pages, Java Server Pages, Cold Fusion, and PHP are often used on web servers. A server-side implementation of JavaScript is also available.

Server-side programs are heavily used on the Web. Almost every time you type information into a form and press a button to send it to a website, the data is processed by a server-side application.

The main difference between JavaScript and server-side languages is that JavaScript applications execute on the client (the web browser) and server-side applications execute on the web server. The main disadvantage of this approach is that, because the data must be sent to the web server and back, response time might be slow.

On the other hand, CGI can do things JavaScript can't do. In particular, it can read and write files on the server and interact with other server components, such as databases. Although a client-side JavaScript program can read information from a form and then manipulate it, it can't store the data on the web server.

JavaScript is often used in conjunction with server-side languages. In its simplest form, this means JavaScript handles client-side chores such as form validation, whereas a server-side language receives data and stores it in a database. Using AJAX, this interaction can be instantaneous and does not even require loading a new page.

Did you Know?
CGI and server-side programming are outside the focus of this book. You can learn more about these technologies with other Sams books, including Teach Yourself CGI Programming in 24 Hours, Teach Yourself Perl in 24 Hours, and Teach Yourself PHP in 24 Hours. See Appendix A, "Other JavaScript Resources," for more sources of information.

Summary

[wax ka badal]

During this hour, you've learned what web scripting is and what JavaScript is. You've also learned how to insert a script into an HTML document or refer to an external JavaScript file, what sorts of things JavaScript can do, and how JavaScript differs from other web languages.

If you're waiting for some real JavaScript code, look no further. The next hour, "Creating Simple Scripts," guides you through the process of creating several working JavaScript examples. You'll also learn about the tools you'll need to work with JavaScript.

Q1:

Do I need to test my JavaScript on more than one browser?

A1:

In an ideal world, any script you write that follows the standards for JavaScript will work in all browsers, and 90% of the time that's true in the real world. But browsers do have their quirks, and you should test your scripts on Internet Explorer and Firefox at a minimum.

Q2:

If I plan to learn Java or CGI anyway, will I have any use for JavaScript?

A2:

Certainly. JavaScript is the ideal tool for many applications, such as form validation. Although Java and CGI have their uses, they can't do all that JavaScript can do.

Q3:

Are there browsers out there that don't support JavaScript?

A3:

Yes. A few niche browsers, such as text-based browsers and tools for blind users, have partial JavaScript support or no support. Mobile phone browsers often support little or no JavaScript. Finally, many users of Internet Explorer or Firefox have JavaScript support turned off, and some corporate firewalls and ad-blocking software block JavaScript. Hour 2 describes how to account for browsers that don't support JavaScript.

Quiz Questions

[wax ka badal]

Test your knowledge of JavaScript by answering the following questions:

  1. Why do JavaScript and Java have similar names?
    1. JavaScript is a stripped-down version of Java.
    2. Netscape's marketing department wanted them to sound related.
    3. They both originated on the island of Java.
  2. When a user views a page containing a JavaScript program, which machine actually executes the script?
    1. The user's machine running a web browser
    2. The web server
    3. A central machine deep within Netscape's corporate offices
  3. Which of the following languages is supported by both Microsoft Internet Explorer and Netscape?
    1. VBScript
    2. ActiveX
    3. JavaScript

Quiz Answers

[wax ka badal]

1. b. Although some of the syntax is similar, JavaScript got its Java-based name mostly because of a marketing relationship.

2. a. JavaScript programs execute on the web browser. (There is actually a server-side version of JavaScript, but that's another story.)

3. c. JavaScript is supported by both Netscape and Internet Explorer, although the implementations are not identical.

Exercises

[wax ka badal]

If you want to learn a bit about JavaScript or check out the latest developments before you proceed with the next hour, perform these activities:

  • Visit this book's website to check for news about JavaScript and updates to the scripts in this book.
  • View some of the examples on this book's website to see JavaScript in action.

-->