Main Page

To hide or not to hide

<input type=”button” value=”Call Function” onclick=”sayHi()” />
</body>
</html>
Here, the
<input/>
tag is used to create a button that calls
sayHi()
when clicked. The
onclick
attribute specifies an
event handler
, which is the code that responds to a given event. Events and event
handlers are discussed further in Chapter 9, “All about Events.”
Note that JavaScript begins running as soon as the page begins loading, so it is possible to call function
that doesn’t exist yet. In the previous example, you can cause an error by placing the original
<script/>
tag after the function call:
<html>
<head>
<title>Title of Page</title>
</head>
<body>
<script language=”JavaScript”>
sayHi();
</script>
<p>This is the first text the user will see.</p>
<script language=”JavaScript”>
function sayHi() {
alert(“Hi”);
}
</script>
</body>
</html>
This example causes an error because
sayHi()
is called before it is defined. Because JavaScript is load-
ing top-down, the function
sayHi()
does not exist until the second
<script/>
tag is encountered.
Be aware of this problem and, as mentioned previously, use events and event handlers to call your
JavaScript functions.
To hide or not to hide
When JavaScript was first introduced, only one browser supported it, so concern arose over how the
nonsupporting browsers would deal with the
<script/>
tag and the code contained within. To that
end, a format was devised to hide code from older browsers (which is a phrase that can still be found in
the source code of a great many Web sites on the Internet today). The following method uses HTML
comments around inline code so that other browsers won’t render the code to the screen:
<script language=”JavaScript”><!-- hide from older browsers
function sayHi() {
alert(“Hi”);
}
//-->
</script>
The first line begins an HTML comment immediately after the opening
<script>
tag. This works
because the browser still considers the rest of that line as part of HTML, with JavaScript code beginning
129
JavaScript in the Browser
08_579088 ch05.qxd 3/28/05 11:37 AM Page 129


JavaScript EditorFree JavaScript Editor     Ajax Editor


©