JavaScript Editor JavaScript Validator     JavaScript Editor 



Team LiB
Previous Section Next Section

The <script> Tag and Your First Simple JavaScript Program

We've discussed the subject of JavaScript for long enough; now let's look at how we put it into our web page. In this section, we'll write our first piece of JavaScript code.

Inserting JavaScript in a web page is much like inserting any other HTML content; we use tags to mark the start and end of our script code. The tag we use to do this is the <script> tag. This tells the browser that the following chunk of text, bounded by the closing </script> tag, is not HTML to be displayed, but rather script code to be processed. We call the chunk of code surrounded by the <script> and </script> tags a script block.

Basically when the browser spots <script> tags, instead of trying to display the contained text to the user, it uses the browser's built-in JavaScript interpreter to run the code's instructions. Of course, the code might give instructions about changes to the way the page is displayed or what is shown in the page, but the text of the code itself is never shown to the user.

We can put the <script> tags inside the header (between the <head> and </head> tags), or inside the body (between the <body> and </body> tags) of the HTML page. However, although we can put them outside these areas, for example, before the <html> tag or after the </html> tag, this is not permitted in the web standards and so is considered bad practice.

The <script> tag has a number of attributes, but the most important one for us are the language and type attributes. As we saw earlier, JavaScript is not the only scripting language available, and different scripting languages need to be processed in different ways. We need to tell the browser which scripting language to expect so that it knows how to process it. There are no prizes for guessing that the language attribute, when using JavaScript, takes the value JavaScript. So, our opening script tag will look like this:

<script language="JavaScript" type="text/javascript">

Including the language attribute is good practice, but within a web page it can be left off. Browsers such as Internet Explorer (IE) and Netscape Navigator (NN) default to a script language of JavaScript. This means that if the browser encounters a <script> tag with no language attribute set, it assumes that the script block is written in JavaScript. However, it is good practice to always include the language attribute.

In some situations JavaScript is not the default language, such as when script is run server-side (see Chapter 16), so we need to specify the language and sometimes the version of JavaScript that our web page requires. However, when not specifying the language attribute will cause problems, I'll be sure to warn you.

However, the web standards have depreciated the requirements for the language attribute; this means the final aim is for its removal. In its place we have the type attribute, and this is made mandatory by the web standards, although most current browsers will let us get away without including it. In the case of script, we need to specify that the type is text/JavaScript, as follows:

<script type="text/javascript">

However, older browsers do not support the type attribute, so for compatibility it's best to include both, as shown here:

<script language="JavaScript" type="text/javascript">

Also note that we can't currently specify the JavaScript version with the type attribute, only with the language attribute.

OK, let's take a look at our first page containing JavaScript code.

Try It Out – Painting the Document Red

We'll try out a simple example of using JavaScript to change the background color of the browser. In your text editor (I'm using Windows NotePad), type in the following:

<html>
<body BGCOLOR="WHITE">
<p>Paragraph 1</p>
<script language="JavaScript" type="text/javascript">
   document.bgColor = "RED";
</script>
</body>
</html>

Save the page as ch1_examp1.htm to a convenient place on your hard drive. Now load it into your web browser. You should see a red web page with the text Paragraph 1 in the top left-hand corner. But wait—didn't we set the <body> tag's BGCOLOR attribute to white? OK, let's look at what's going on here.

How It Works

The page is contained within <html> and </html> tags. This then contains a <body> element. When we define the opening <body> tag, we use HTML to set the page's background color to white.

<BODY BGCOLOR="WHITE">

Then, we let the browser know that our next lines of code are JavaScript code by using the <script> start tag.

<script language="JavaScript" type="text/javascript">

Everything from here until the close tag, </script>, is JavaScript and is treated as such by the browser. Within this script block, we use JavaScript to set the document's background color to red.

document.bgColor = "RED";

What we might call the page is known as the document when scripting in a web page. The document has lots of properties, including its background color, bgColor. We can reference properties of the document by writing document, then putting a dot, then the property name. Don't worry about the use of the document at the moment; we'll be looking at it in depth later in the book.

Note that the preceding line of code is an example of a JavaScript statement. Every line of code between the <script> and </script> tags is called a statement, although some statements may run on to more than one line.

You'll also see that there's a semicolon (;) at the end of the line. We use a semicolon in JavaScript to indicate the end of a statement. In practice, JavaScript is very relaxed about the need for semicolons, and when you start a new line, JavaScript will usually be able to work out whether you mean to start a new line of code. However, for good coding practice, you should use a semicolon at the end of statements of code, and a single JavaScript statement should fit onto one line and shouldn't be continued onto two or more lines. Moreover, you'll find there are times when you must include a semicolon, which we'll come to later in the book.

Finally, to tell the browser to stop interpreting our text as JavaScript and start interpreting it as HTML, we use the script close tag:

</script>

We've now looked at how the code works, but we haven't looked at the order in which it works. When the browser loads in the web page, the browser goes through it, rendering it tag by tag from top to bottom of the page. This process is called parsing. The web browser starts at the top of the page and works its way down to the bottom of the page. The browser comes to the <body> tag first and sets the document's background to white. Then it continues parsing the page. When it comes to the JavaScript code, it is instructed to change the document's background to red.

Try It Out – The Way Things Flow

Let's extend the previous example to demonstrate the parsing of a web page in action. Type the following into your text editor:

<html>
<body BGCOLOR="WHITE">
<p>Paragraph 1</p>
<script language="JavaScript" type="text/javascript">
   // Script block 1
   alert("First Script Block");
</script>
<p>Paragraph 2</p>
<script language="JavaScript" type="text/javascript">
   // Script block 2
   document.bgColor = "RED";
   alert("Second Script Block");
</script>
<p>Paragraph 3</p>
</body>
</html>

Save the file to your hard drive as ch1_examp2.htm, and then load it into your browser. When you load the page you should see the first paragraph, Paragraph 1, appear followed by a message box displayed by the first script block. The browser halts its parsing until you click the OK button. As you can see in Figure 1-1, the page background is white, as set in the <body> tag, and only the first paragraph is currently displayed.

Click To expand
Figure 1-1

Click the OK button, and the parsing continues. The browser displays the second paragraph, and the second script block is reached, which changes the background color to red. Another message box is displayed by the second script block, as shown in Figure 1-2.

Click To expand
Figure 1-2

Click OK, and again the parsing continues, with the third paragraph, Paragraph 3, being displayed. The web page is complete, as shown in Figure 1-3.

Click To expand
Figure 1-3

How It Works

The first part of the page is the same as in our earlier example. The background color for the page is set to white in the definition of the <body> tag, and then a paragraph is written to the page.

<html>
<body BGCOLOR="WHITE">
<p>Paragraph 1</p>

The first new section is contained in the first script block.

<script language="JavaScript" type="text/javascript">
   // Script block 1
   alert("First Script Block");
</script>

This script block contains two lines, both of which are new to us. The first line

   // Script block 1

is just a comment, solely for our benefit. The browser recognizes anything on a line after a double forward slash (//) to be a comment and does not do anything with it. It is useful for us as programmers, because we can add explanations to our code that make it easier for us to remember what we were doing when we come back to our code at a later date.

The alert() function in the second line of code is also new to us. Before we can explain what it does, we need to explain what a function is.

We will define functions more fully in Chapter 3, but for now we just need to think of them as pieces of JavaScript code that we can use to do certain tasks. If you have a background in math, you may already have some idea of what a function is: A function takes some information, processes it, and gives you a result. A function makes life easier for us as programmers because we don't have to think about how the function does the task but can just concentrate on when we want the task done.

In particular, the alert() function enables us to alert or inform the user about something, by displaying a message box. The message to be given in the message box is specified inside the parentheses of the alert() function and is known as the function's parameter.

The message box that's displayed by the alert() function is modal. This is an important concept, which we'll come across again. It simply means that the message box won't go away until the user closes it by clicking the OK button. In fact, parsing of the page stops at the line where the alert() function is used and doesn't restart until the user closes the message box. This is quite useful for this example, because it allows us to demonstrate the results of what has been parsed so far: The page color has been set to white, and the first paragraph has been displayed.

Once you click OK, the browser carries on parsing down the page through the following lines:

<p>Paragraph 2</p>
<script language="JavaScript" type="text/javascript">
   // Script block 2
   document.bgColor = "RED";
   alert("Second Script Block");
</script>

The second paragraph is displayed, and the second block of JavaScript is run. The first line of the script block code is another comment, so the browser ignores this. We saw the second line of the script code in our previous example—it changes the background color of the page to red. The third line of code is our alert() function, which displays the second message box. Parsing is brought to a halt until we close the message box by clicking OK.

When we close the message box, the browser moves on to the next lines of code in the page, displaying the third paragraph and finally ending our web page.

<p>Paragraph 3</p>
</body>
</html>

Another important point raised by this example is the difference between setting properties of the page, such as background color, via HTML and doing the same thing using JavaScript. The method of setting properties using HTML is static: A value can be set only once and never changed again using HTML. Setting properties using JavaScript enables us to dynamically change their values. By dynamic, I simply mean something that can be changed and whose value or appearance is not set in stone.

Our example is just that, an example. In practice if we wanted the page's background to be red, we would set the <body> tag's BGCOLOR attribute to "RED", and not use JavaScript at all. Where we would want to use JavaScript is where we want to add some sort of intelligence or logic to the page. For example, if the user's screen resolution is particularly low, we might want to change what's displayed on the page; with JavaScript, we can do this. Another reason for using JavaScript to change properties might be for special effects, for example, making a page fade in from white to its final color.


Team LiB
Previous Section Next Section


JavaScript Editor JavaScript Validator     JavaScript Editor


©

orange county powder coating . starting a bounce house business