Java Reference
In-Depth Information
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.
You 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 you can put them
outside these areas — for example, before the <html> tag or after the </html> tag — this is not permit-
ted in the web standards and so is considered bad practice.
The <script> tag has a number of attributes, but the most important one is type. As you saw earlier,
JavaScript is not the only scripting language available, and different scripting languages need to be
processed in different ways. You need to tell the browser which scripting language to expect so that it
knows how to process that language. Your opening script tag will look like this:
<script type=”text/javascript”>
Including the type attribute is good practice, but within a web page it can be left off. Browsers such as
IE and Firefox use JavaScript as their default script language. This means that if the browser encounters
a <script> tag with no type attribute set, it assumes that the script block is written in JavaScript.
However, use of the type attribute is specifi ed as mandatory by W3C, which sets the standards for HTML.
Okay, let's take a look at the fi rst page containing JavaScript code.
Try It Out Painting the Page Red
This is a simple example of using JavaScript to change the background color of the browser. In your text
editor (we're using Windows Notepad), type the following:
<html>
<body bgcolor=”WHITE”>
<p>Paragraph 1</p>
<script 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 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 defi ne 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 type=”text/javascript”>
Search WWH ::




Custom Search