Information Technology Reference
In-Depth Information
The code that creates these messages is remarkably simple. Listing 1-6 integrated the
code into the chores.html page we saw in the CSS example above.
Listing 1-6. chores.html with JavaScript reference
<html>
<head>
<title> Family Chore List </title>
<link rel="stylesheet" type="text/css" href="patriotic.css" />
<script type="text/javascript">
function ShowWarning() {
alert("Mittens - your mousing numbers are down this week - NO CATNIP FOR YOU");
}
</script>
</head>
<body onload=ShowWarning();>
<h1>Family Chore List</h1>
<ul>
<li><strong>Tommy</strong>: Take out the trash</li>
<li><strong>Beth</strong>: Clean out the fridge. </li>
<li><strong>Mittens</strong>: catch mice. </li>
</ul>
</body>
</html>
Let's start by talking about the new section of code right below the CSS link, inside the
head section, with the tag script . The script tag tells the browser that a section of
scripting code (in this case, of the type text/javascript ) is about to be given. The
browser then interprets the code. Since it's in the head section, the browser simply stores
this code for later use. This piece of code is called a function, which you can think of as
a list of commands wrapped up in a “shortcut”. Here the command is another function
named alert . As you can imagine, JavaScript functions can get quite complex, with
functions including other functions and interacting with user input.
Once the function is loaded into the browser's menu, we need to tell the browser when
we want to execute it. In this case, I've changed the body tag to include the line
onload=ShowWarning(); . This tells the browser that, when the page is loaded, I want it to
run the function ShowWarning . The two parentheses indicate a spot where I could include
information to pass to the function. This becomes useful for creating things like
calculators or for checking input in a form. For example, I could write up something like
Listing 1-7.
Listing 1-7. chores.html with JavaScript reference passing a variable
<html>
<head>
<title> Family Chore List </title>
<link rel="stylesheet" type="text/css" href="patriotic.css" />
<script type="text/javascript">
function ShowWarning(catname) {
alert(catname + " - your mousing numbers are down this week - NO CATNIP FOR YOU");
}
</script>
</head>
<body onload=ShowWarning("Mittens");>
<h1>Family Chore List</h1>
 
Search WWH ::




Custom Search