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

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

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Dissecting Our First Script

Our first JavaScript script wrote something in a web page—so how did it do that? We'll take it apart step by step here to see what's going on. First of all, like all scripts, we placed this script inside a <SCRIPT> HTML element so that the browser would know it's dealing with a script of some kind:

<HTML>
  <HEAD>
    <TITLE>Our first script!</TITLE>
  </HEAD>

  <BODY>
    <H1>Here we go!</H1>
    <SCRIPT LANGUAGE="JavaScript">
    .
    .
    .
    </SCRIPT>
  </BODY>
</HTML>

What is this <SCRIPT> element all about? Let's take a look.

The <SCRIPT> Element

The <SCRIPT> element will be an important one for us, so here are all its attributes, as set by W3C in the HTML 4.01 specification (http://www.w3.org/TR/html401):

  • CHARSET. Specifies the character encoding of the script contents. Set to a language character set string. (The default is ISO-8859-1.)

  • CLASS. Class of the element (used for rendering). Supported in IE4, IE5, and IE6.

  • DEFER. Indicates to the browser that the script is not going to generate any document content (which means the browser can continue parsing and drawing the page). Standalone attribute. Supported in IE4, IE5, and IE6.

  • EVENT. Gives the event the script is written for. Set to an event name (see "Using <SCRIPT FOR>" in this chapter for all the details). Supported in IE4, IE5, IE6, and NS6.

  • FOR. Indicates which element is bound to the script. Set to an HTML element or element ID. Supported in IE4, IE5, and IE6.

  • ID. Unique alphanumeric identifier for the tag, which you can use to refer to it. Supported in IE4, IE5, IE6, and NS6.

  • LANGUAGE. Sets the scripting language. This attribute is required if the SRC attribute is not set and is optional otherwise. Set to the name of a scripting language, such as JavaScript or VBScript. Supported in IE3, IE4, IE5, IE6, NS3, NS4, and NS6.

  • SRC. Gives an external source for the script code. Set to an URL. Supported in IE3, IE4, IE5, IE6, NS3, NS4, and NS6.

  • TITLE. Holds additional information (which might be displayed in tool tips) for the element. Supported in IE4, IE5, and IE6.

  • TYPE. Indicates the Multipurpose Internet Mail Extension (MIME) type of the scripting code. Set to an alphanumeric MIME type. Meant to replace the LANGUAGE attribute. Supported in IE4, IE5, IE6, and NS6.

"JScript" if I wanted to target only the Internet Explorer, but that browser recognizes "JavaScript" as well as "JScript," and treats the two identically. There are other types of scripts out there, such as VBScript and PerlScript, so specifying the language you're using can be important. (In fact, the default if you omit the LANGUAGE attribute in both the Netscape Navigator and the Internet Explorer is "JavaScript.")

It's also worth noting that in the most recent version of HTML, version 4.01 as specified by W3C (you can see the specification at http://www.w3.org/TR/ html401), the LANGUAGE attribute has been replaced by the TYPE attribute. And, instead of setting TYPE to "JavaScript," you set it to "text/javascript." This new way of doing things is supported in both Netscape Navigator and Internet Explorer. However, the standard method of using the LANGUAGE attribute will be around for a long, long time yet in both the Netscape Navigator and Internet Explorer.

Hiding Scripts from Older Browsers

Note the next part of our script—it looks as though it's being hidden by an HTML comment (that is, <!-- -->):

<HTML>
  <HEAD>
    <TITLE>Our first script!</TITLE>
  </HEAD>

  <BODY>
    <H1>Here we go!</H1>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    document.write("Hello from JavaScript!")
    // -->
    </SCRIPT>
  </BODY>
</HTML>

What's going on here? In this case, I'm hiding our JavaScript from older browsers that don't support JavaScript. If a browser doesn't support JavaScript, it may display just our entire script in the web page without executing it, which looks less than professional. To avoid that, you can enclose the actual script statements in an HTML comment, as we've done here.

What really happens is that JavaScript-enabled browsers know enough to skip over an opening HTML comment tag, <!--, in <SCRIPT> elements. What about the closing comment tag, -->? To make sure the browser skips over that tag too, we're using a JavaScript single-line comment, which starts with two forward slashes (//). When JavaScript sees a comment marker, //, it ignores the rest of the line, which enables you to add comments to your code that programmers can read and JavaScript won't. Following the // marker here, I use the --> HTML closing comment tag so that older browsers will think the HTML comment is complete and will not show any of our script in the web page itself.

Most browsers you encounter will support JavaScript, but those that don't aren't necessarily old—they can be text-only browsers, or PDA browsers. Which means that you can't expect non-JavaScript browsers to fade away—which means it's good practice to surround your code with HTML comments. In fact, there's an entire HTML tag expressly for use with browsers that don't support JavaScript: <NOSCRIPT>.

Using <NOSCRIPT>

You might want to provide a non-JavaScript version of a web page for non-JavaScript browsers. You can do that in a <NOSCRIPT> element. Browsers that support JavaScript ignore this element and its contents. However, only the <NOSCRIPT> and </NOSCRIPT> tags are ignored by non-JavaScript browsers—all the HTML and text between these tags is still displayed.

That means you can put HTML for a non-JavaScript browser in a <NOSCRIPT> element, including links or redirection directives to a non-JavaScript page. Alternatively, you might just tell the user to get a browser that supports JavaScript, like this:

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

<HTML>
  <HEAD>
    <TITLE>
      Our first script!
    </TITLE>
  </HEAD>

  <BODY>
    <H1>Here we go!</H1>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
      document.write("Hello from JavaScript!")
    // -->
    </SCRIPT>
    <NOSCRIPT>
      Hey, get a browser that supports JavaScript!
    </NOSCRIPT>
   </BODY>
</HTML>

Here's an example: Microsoft Word is capable of opening HTML pages, but it doesn't support JavaScript. You can see the preceding page opened in Word in Figure 1.4, showing our prompt to the user about getting a new browser.

Figure 1.4 Using the <NOSCRIPT> element.

Here are the attributes for the <NOSCRIPT> element:

  • CLASS. Class of the element (used for rendering).

  • DIR. Gives the direction of directionally neutral text (text that doesn't have inherent direction in which you should read it). Possible values: LTR (left-to-right text or table) and RTL (right-to-left text or table).

  • ID. Unique alphanumeric identifier for the tag, which you can use to refer to it. Supported in IE4, IE5, IE6, and NS6.

  • LANG. Base language used for the tag.

  • STYLE. Inline style indicating how to render the element. Supported in IE6 and NS6.

  • TITLE. Holds additional information (which might be displayed in tool tips) for the element.

We have yet to dissect the part of our first script where we're actually using JavaScript itself. Let's do that now.

Writing JavaScript

Here's the actual JavaScript statement that does the work of displaying the text Hello from JavaScript!:

<HTML>
  <HEAD>
    <TITLE>Our first script!</TITLE>
  </HEAD>

  <BODY>
    <H1>Here we go!</H1>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    document.write("Hello from JavaScript!")
    // -->
    </SCRIPT>
  </BODY>
</HTML>

Here, we want to get something done in the browser—that is, display your message in a web page—and to do that, we have to interact with the browser. You interact with the browser through a set of objects, as we've discussed. In this case, we'll use the document object, which corresponds to the body of a web page (as well as several other parts).

Objects such as the document object have properties, which, like HTML attributes, enable you to configure a web page, setting its color and so on. They also have methods, which let you make something happen actively, such as writing in a web page. They also can handle events, which enable you to respond to user actions such as mouse clicks. Properties, methods, and events are all going to be very important to us, and we'll see more about them in this chapter; in this example, we're using the write method of the document object to write some text to our HTML page:

document.write("Hello from JavaScript!")

Note that we send the actual text to write to the web page, enclosed in quotation marks, to the write method by enclosing that text in parentheses. And that's all it takes; when this JavaScript statement is executed, our message is written to the web page. We've been able to make the document object do something for us by using one of its methods. We'll see all the methods of the various browser objects in this book laid out in detail.

Here's another thing to note—JavaScript is case-sensitive, which means that, unlike HTML, capitalization counts. If we had written this instead, JavaScript wouldn't have executed it:

Document.Write("Hello from JavaScript!")

That completes our first script; we've made considerable progress already. Let's take a look at a few more foundation issues now that will become important as we progress.

What About Semicolons?

JavaScript was written to follow the lead of Java in many ways, and one of those ways was to require a semicolon (;) at the end of each statement. Technically, we should have written our JavaScript statement followed by a semicolon, like this:

<HTML>
  <HEAD>
    <TITLE>Our first script!</TITLE>
  </HEAD>

  <BODY>
    <H1>Here we go!</H1>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    document.write("Hello from JavaScript!");
    // -->
    </SCRIPT>
  </BODY>
</HTML>

However, through popular usage, the semicolon is almost completely a thing of the past in JavaScript. Browsers don't require it, and programmers don't use it for the most part. Following common usage, we won't use it here either.

Tip

In at least one case, however, you must use semicolons. You can place two or more JavaScript statements on the same line if you want to; but if you do, you need to separate them with semicolons.

Commenting Your JavaScript

We've already seen that JavaScript supports a one-line comment with the // marker. JavaScript will stop reading anything on a line past //, so you can add comments for people to read to your code like this:

<HTML>
  <HEAD>
    <TITLE>
      Welcome To JavaScript
    </TITLE>

  </HEAD>

  <BODY>

    <SCRIPT LANGUAGE="JavaScript">
    <!--
      //Write "Welcome to JavaScript!" in the page.
      document.write("Welcome to JavaScript!")
    //-->
    </SCRIPT>

    <NOSCRIPT>
      Sorry, your browser doesn't support JavaScript!
    </NOSCRIPT>

    <H1>
        Welcome To JavaScript!
    </H1>
  </BODY>
</HTML>

In fact, JavaScript also supports a second type of comment, which you can use for multiple lines. This comment starts with /* and ends with */. When JavaScript sees /*, it ignores everything else until it sees */. Here's an example:

    <SCRIPT LANGUAGE="JavaScript">
    <!--
      /* This script
        writes "Welcome to JavaScript!" 
        in the page.
      */
      document.write("Welcome to JavaScript!")
    //-->
    </SCRIPT>

Or you can create an entire comment block like this:

    <SCRIPT LANGUAGE="JavaScript">
    <!--
      /*-----------------------------------
      |  This script           |
      |  writes "Welcome to JavaScript!" |
      |  in the page.          |
      -----------------------------------*/
      document.write("Welcome to JavaScript!")
    //-->
    </SCRIPT>

Where Does the <SCRIPT> Element Go?

One question to ask is where exactly is the <SCRIPT> element supposed to go in a web page. When JavaScript first came out, many purists insisted that the <SCRIPT> element could go only in a page's head section, because the head contained meta information about the page that wasn't supposed to be displayed:

<HTML>
  <HEAD>
    <TITLE>Our first script!</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    .
    .
    .
    // -->
    </SCRIPT>
  </HEAD>

  <BODY>
    <H1>Here we go!</H1>
  </BODY>
</HTML>

However, JavaScript outgrew that and started to be able to create elements that were indeed to be displayed, as in our first script, which displayed some text in a web page. That can happen when the body of the page is loaded; so when you're writing to the web page with document.write, you can place your script in the body, not in the head:

<HTML>
  <HEAD>
    <TITLE>Our first script!</TITLE>
  </HEAD>

  <BODY>
    <H1>Here we go!</H1>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    document.write("Hello from JavaScript!")
    // -->
    </SCRIPT>
  </BODY>
</HTML>

The reason for this is that when the head is loaded and your script executes, the body section of the page, which it works with, may not have been loaded yet. In fact, you can have scripts in both the head and the body:

<HTML>
  <HEAD>
    <TITLE>Our first script!</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    .
    .
    .
    </SCRIPT>
  </HEAD>

  <BODY>
    <H1>Here we go!</H1>
    <SCRIPT LANGUAGE="JavaScript">
    .
    .
    .
    </SCRIPT>
  </BODY>
</HTML>

Alternatively, you can have multiple scripts in the head and/or the body:

<HTML>
  <HEAD>
    <SCRIPT LANGUAGE="JavaScript">
    .
    .
    .
    </SCRIPT>
    <TITLE>Our first script!</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    .
    .
    .
    </SCRIPT>
  </HEAD>

  <BODY>
    <H1>Here we go!</H1>
  </BODY>
</HTML>

So the answer to the question of where the <SCRIPT> element goes is this: Wherever it fits best. Usually, it's best to place <SCRIPT> elements in the head section of a web page. When you're writing to the web page directly, however, or may otherwise end up trying to access body elements before the body is loaded, it can be a good idea to place the <SCRIPT> element in the body of the web page.

Tip

In fact, there's another option: You can even place code that accesses the page's body in the head section of a page if you let the browser itself tell you when it's safe to run that code. See the discussion in "When Does a Script Run?" later in this chapter to learn how to run a script only after the whole page has loaded into the browser.

There are still more options to consider here; we've placed all our code in the web page itself—but you can store JavaScript outside the web page and still have it downloaded with that page.

Using Separate Script Files

If you want to store your JavaScript code in a file outside the web page you'll use it in, store it in a file with the extension .js. This can be a good idea when you're dealing with cross-browser issues, for example, because you can load one .js file for one browser and another .js file for another browser.

To associate a .js script file with a <SCRIPT> element, you use the <SCRIPT> element's SRC attribute, like this. (Note that the <SCRIPT> element is empty here, as it should be when you use the SRC attribute.)

<HTML>
  <HEAD>
    <TITLE>
      Here's my script!
    </TITLE>
    <SCRIPT LANGUAGE="JavaScript" SRC="script.js">
    </SCRIPT>
  </HEAD>

  <BODY>
    <H1>Like my script?</H1>
  </BODY>
</HTML>

You set the SRC attribute to a URL, so you can even get the .js file from another server, like this:

<HTML>
  <HEAD>
    <TITLE>
      Here's my script!
    </TITLE>
    <SCRIPT LANGUAGE="JavaScript" SRC="http://www.myjavascripts/steve/script.js">
    </SCRIPT>
  </HEAD>

  <BODY>
    <H1>Like my script?</H1>
  </BODY>
</HTML>

The .js file, script.js here, contains only the code you want to execute, like this:

document.write("Hello from JavaScript!")

Tip

Note, however, that when you're doing something like what this statement does—write to the body of a document—you can run into problems with external script files, because the browser may well load the external script file before the body is fully loaded, which means your JavaScript will not do anything.

Specifying the Language Version

You can use the LANGUAGE attribute in <SCRIPT> elements to specify the version of JavaScript you want to use. If your script is written for JavaScript 1.1, for example, you can specify that you want to use that version of the language like this:

<HTML>
  <HEAD>
    <TITLE>Our first script!</TITLE>
    <SCRIPT LANGUAGE="JavaScript 1.1">
    .
    //JavaScript 1.1 Code
    .
    </SCRIPT>
  </HEAD>

  <BODY>
    <H1>Here we go!</H1>
  </BODY>
</HTML>

Note that if the browser you're working with doesn't support JavaScript 1.1, your code won't be run. You can code for different levels of JavaScript like this, where I'm using multiple <SCRIPT> elements to handle browsers that support JavaScript 1.0, 1.1, and so on—note that these <SCRIPT> elements must be in ascending order:

<HTML>
  <HEAD>
    <TITLE>Our first script!</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    .
    //JavaScript 1.0 Browsers
    .
    </SCRIPT>
    <SCRIPT LANGUAGE="JavaScript 1.1">
    .
    //JavaScript 1.1 Browsers
    .
    </SCRIPT>
    <SCRIPT LANGUAGE="JavaScript 1.2">
    .
    //JavaScript 1.2 Browsers
    .
    </SCRIPT>
    <!--
    document.write("Hello from JavaScript!")
    // -->
    </SCRIPT>
  </HEAD>

  <BODY>
    <H1>Here we go!</H1>
  </BODY>
</HTML>

Tip

This is also a good way to determine what version of JavaScript a browser supports—<SCRIPT> elements specifying more recent versions will not be executed.

We've seen what <SCRIPT> elements are for, where they go, and what their attributes are for. But when does the code in them actually run? In our first example, the code ran automatically, as soon as the page loaded. However, that's not a good thing for every page, of course; for example, you might be writing a web page that calculates loan interest, and it wouldn't be a good idea to do anything until the user entered some data. So when do scripts run?

When Does a Script Run?

Code in a JavaScript script runs at three main times:

  • While the document is loading

  • Just after the document loads

  • When the user performs some action

I'll take a look at these in overview, because knowing when a script will run is an important part of our JavaScript foundation. Note, however, that this is only an overview, because it deals with some topics, such as functions, that we won't see until Chapter 3, "The JavaScript Language: Loops, Functions, and Errors."

Our first script ran automatically as the document loaded, because we simply placed our JavaScript statements in a <SCRIPT> element:

<HTML>
  <HEAD>
    <TITLE>Our first script!</TITLE>
  </HEAD>

  <BODY>
    <H1>Here we go!</H1>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    document.write("Hello from JavaScript!")
    // -->
    </SCRIPT>
  </BODY>
</HTML>

In this case, the browser runs our code as that code is loaded from the HTML document the browser is opening.

However, JavaScript code does not have to run immediately as it is loaded into the browser—you can wait until after the entire document has been loaded before running your code. That's often a good idea because HTML documents load piece by piece, which means you might find yourself trying to work with an HTML element that hasn't been loaded into the browser yet, and that would cause an error.

You can let the browser inform you when a web page is fully loaded with an event. When an event occurs in a browser, you know that something happened—for example, the user pressed a mouse button or a key on the keyboard. You can handle events in JavaScript by specifying code to run when a particular event occurs, such as when a button is clicked in a web page.

We'll cover events in detail in Chapter 6, "Using Core HTML Methods and Events," but here's a preview (which you can skip and come back to later if you want). The event that occurs when a page is fully loaded is the onload event, and like other events, you can handle it using attributes of HTML elements—in this case, you use the ONLOAD attribute of the <BODY> element. (We'll see the onload event in depth in Chapter 8, "Using window and frame Methods and Events"—see the section "Window Loading and Unloading" in that chapter.)

We'll need some way of connecting the code we want to run to the <BODY> element's ONLOAD attribute, and we can do that with a JavaScript function. We'll see all the details about functions in Chapter 3; what's important to know here is that they will give us a way to collect our code into easily handled packages that are run only when you want them to be run (not automatically as the browser reads your code).

Suppose, for example, that I want to use the window object's alert method to display a message in a simple dialog box—called an alert box—indicating that the page has finished loading. To do that, I'll create a function named alerter and connect this function to the ONLOAD attribute of the <BODY> element. (Chapter 3 contains details about creating functions.) Doing so makes sure that the code in that function is run only when the page is fully loaded. Here's how this looks in JavaScript:

(Listing 10-03.html on the web site)

<HTML>
  <HEAD>
    <TITLE>
      Executing Scripts After a Document Loads
    </TITLE>
    <SCRIPT LANGUAGE="JavaScript">
      <!--
      function alerter() 
      {
        window.alert("All loaded.")
      }
      // -->
    </SCRIPT>
  </HEAD>

  <BODY ONLOAD="alerter()">
    <H1>Executing Scripts After a Document Loads</H1>
  </BODY>
</HTML>

That's all it takes—now that we've packaged our code in a function, that code is run only when we want it to run, not automatically when the page loaded, as would happen if the code were not enclosed in a function. You can see the result of this code in Figure 1.5 in the Internet Explorer, and Figure 1.6 in the Netscape Navigator, where those browsers are being made to display an alert box to indicate that the current web page has finished loading.

Figure 1.5 Using ONLOAD in the Internet Explorer.

Figure 1.6 Using ONLOAD in the Netscape Navigator.

We've seen how loading a page can trigger an event—the onload event—but user actions, such as button clicks, can trigger events as well. We'll see how this works starting in Chapters 6, "Using Core HTML Methods and Events," and and 12, "Working with Forms, Buttons, Checkboxes, and Radio Buttons," but here's a preview. For example, just as we used the ONLOAD attribute of the <BODY> element to handle onload events, we can also handle button onclick events, which occur when you click a button, with the ONCLICK attribute of HTML button elements. Here's how I can display an alert box when the user clicks a button:

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

<HTML>
  <HEAD>
    <TITLE>
      Executing Scripts in Response to User Action
    </TITLE>
    <SCRIPT LANGUAGE="JavaScript">
      <!--
      function alerter()
      {
        window.alert("You clicked the button!")
      }
      // -->
    </SCRIPT>
  </HEAD>

  <BODY>
    <H1>Executing Scripts in Response to User Action</H1>
    <FORM>
      <INPUT TYPE="BUTTON" ONCLICK="alerter()" VALUE="Click Me!">
    </FORM>
  </BODY>
</HTML>

When the user clicks the button, the function named alerter is run, which displays the alert box. We'll see more on functions in Chapter 3, but what's important to know now is that they'll give us a way to decide when our code should be run, as opposed to letting the browser run that code automatically as the code is loaded from the HTML document.

Inline Scripts

Here's another option that you should be aware of: inline scripts. So far, we've placed all our code in <SCRIPT> elements or .js files, but there actually is another way, for very short code. Instead of connecting a JavaScript function to an event such as the onload event with the ONLOAD attribute, you can actually assign the JavaScript code you want to execute directly to the ONLOAD attribute. For example, here's how I display an alert box with the message All loaded. when a page loads:

<HTML>
  <HEAD>
    <TITLE> 
      Executing Scripts After a Document Loads
    </TITLE>
  </HEAD>

  <BODY ONLOAD="alert('All loaded.')">
    <H1>Executing Scripts After a Document Loads</H1>
  </BODY>
</HTML>

This is a good technique to know for short scripts, but only for short scripts. For anything longer, place your script in a <SCRIPT> element.

Tip

If you want to place multiple statements in an inline script, you must separate them with semicolons.

Using <SCRIPT FOR>

And here's something else—in the Internet Explorer since version 4.0, you can use the <SCRIPT> element's FOR attribute to connect a script to a particular HTML element. For example, here's how I connect a script to the onclick event of the HTML button I've named button1 (I've named the button by setting the NAME attribute in the <INPUT> element that defines the button):

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

<HTML>
  <HEAD>
    <TITLE>
      Using the SCRIPT FOR Element
    </TITLE>
    <SCRIPT FOR="button1" EVENT="onclick" LANGUAGE="JavaScript">
      <!--
      alert("You clicked the button!")
      // -->
    </SCRIPT>
  </HEAD>

  <BODY>
    <H1>Using the SCRIPT FOR Element</H1>
    <FORM NAME="form1">
      <INPUT TYPE="BUTTON" NAME="button1" VALUE="Click Me!">
    </FORM>
  </BODY>
</HTML>

Now when the user clicks the button, an alert box appears with the message You clicked the button! (see Figure 1.7). This won't work in the Netscape Navigator, which will just run the script as soon as the page loads.

This is a useful technique to know to handle events, although it's not much used because it conflicts with the Netscape Navigator. We'll see more on this when we start working with events in Chapter 6.

Figure 1.7 Using SCRIPT FOR in the Internet

  • + Share This
  • 🔖 Save To Your Account