Java Reference
In-Depth Information
Everything from here until the close tag, </script>, is JavaScript and is treated as such by the browser.
Within this script block, you use JavaScript to set the document's background color to red.
document.bgColor = “RED”;
What you might call the page is known as the document for the purpose of scripting in a web page. The
document has lots of properties, including its background color, bgColor . You can reference properties
of the document by writing document , followed by a dot, followed by the property name. Don't worry
about the use of document at the moment; you look at it in greater depth later in the topic.
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. You 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 fi t onto one line rather than continue on to two or more
lines. Moreover, you'll fi nd there are times when you must include a semicolon, which you'll come to
later in the topic.
Finally, to tell the browser to stop interpreting your text as JavaScript and start interpreting it as HTML,
you use the script close tag:
</script>
You've now looked at how the code works, but you 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 bot-
tom 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 fi rst and sets the docu-
ment'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 follow-
ing into your text editor:
<html>
<body bgcolor=”WHITE”>
<p>Paragraph 1</p>
<script type=”text/javascript”>
// Script block 1
alert(“First Script Block”);
</script>
<p>Paragraph 2</p>
<script type=”text/javascript”>
// Script block 2
document.bgColor = “RED”;
alert(“Second Script Block”);
Search WWH ::




Custom Search