Java Reference
In-Depth Information
means of HTML. Setting properties using JavaScript enables you to dynamically change their values.
The term dynamic refers to something that can be changed and whose value or appearance is not set
in stone.
This example is just that, an example. In practice, if you want the page's background to be red, simply
set the background color with CSS (don't use the bgcolor attribute in practice). Where you want to use
JavaScript is where you want to add some sort of intelligence or logic to the page. For example, if the
user's screen resolution is particularly low, you might want to change what's displayed on the page, and
you can do that with JavaScript.
Displaying results in a Web page
trY it out
In this final example, you discover how to write information directly to a web page using JavaScript.
This proves more useful when you're writing the results of a calculation or text you've created using
JavaScript, as you see in the next chapter. For now, you'll just write “Hello World!” to a blank page
using JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Chapter 1, Example 3</title>
</head>
<body>
<p id="results"></p>
<script>
document.getElementById("results").innerHTML = "Hello World!";
</script>
</body>
</html>
Save the page as ch1 _ example3.html to a convenient place on your hard drive. Now load it into your
web browser and you'll see Hello World! in the page. Although it would be easier to use HTML to do
the same thing, this technique will prove useful in later chapters.
The first part of the page is the same as in our earlier examples, but things start to change when you
reach this line:
<p id="results"></p>
You'll notice the <p/> element has been given an ID using the id attribute. This ID must be unique in
the web page, because it is used by JavaScript to identify the specific HTML element in the following
line:
document.getElementById("results").innerHTML = "Hello World!";
Search WWH ::




Custom Search