Java Reference
In-Depth Information
Your first simple JavasCript program
Enough talk about the subject of JavaScript; let's write some! We'll start with a simple example that
changes the background color of the web page.
painting the page red
trY it out
This is a simple example of using JavaScript to change the background color of the browser. In your
text editor, type the following:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Chapter 1, Example 1</title>
</head>
<body bgcolor="white">
<p>Paragraph 1</p>
<script>
document.bgColor = "red";
</script>
</body>
</html>
Save the page as ch1 _ example1.html to a convenient place on your hard drive, and load it into your
web browser. You should see a red web page with the text Paragraph 1 in the top‐left corner. But
wait—don't you set the <body> tag's BGCOLOR attribute to white? Okay, let's look at what's going on
here.
The page is contained within <html> and </html> tags. This block contains a <body> element. When
you define the opening <body> tag, you use HTML to set the page's background color to white:
<body bgcolor="white">
Then you let the browser know that your next lines of code are JavaScript code by using the <script>
start tag:
<script>
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
book.
 
Search WWH ::




Custom Search