A Complete Guide to Web Design

(やまだぃちぅ) #1
380 Chapter 22 – Introduction to JavaScript

JavaScript Basics


Web Design in a Nutshell, eMatter Edition

function openWin(URL) {
aWindow=window.open(URL,"thewindow","toolbar=no,width=350,
height=400,status=no,scrollbars=yes,resize=no,menubar=no");
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<P><A HREF="javascript:openWin('mozart.html');">Mozart</A></P>
<P><A HREF="javascript:openWin('beethoven.html');">Beethoven
</A></P>
<P><A HREF="javascript:openWin('wagner.html');">Wagner</A></P>
</BODY>
</HTML>
The JavaScript inside the<script> tags defines a function, calledopenWin(),
that tells the browser what to do when the function is called. Now look at the
body of the document. TheopenWin()function is being called from the anchor
tags. Let’s take a look at one of those lines:
<A HREF="javascript:openWin('mozart.html');">Mozart</A>
The line starts off as a normal<a href>tag. But the value ofhref is not a stan-
dard URL; it’s a call to a JavaScript function. The wordjavascript:tells the
browser that this will be a JavaScript link. Next, theopenWin() function, which
was defined up in the head of the document, is called. Since the JavaScript call is
in a link, the function will run when the user clicks on the link (the word
“Mozart”). The content in parentheses—('mozart.html');—specifies a value
that will be passed to theopenWin()function. We’ll see what passing is all about
when we look at the function. The rest of the line is a standard link—the hyper-
text and the closing anchor tag.
Now let’s look at theopenWin()function:
function openWin(URL) {
aWindow=window.open(URL,"thewindow","toolbar=no,width=350,
height=400,status=no,scrollbars=yes,resize=no,menubar=no");
}
The first line of code “declares” a new function with the nameopenWin(). The set
of parentheses indicates that the function can take “arguments” or “parameters.”
Arguments are conditions that affect the way the function runs. In this example,
we are going to pass a URL to the function, which will open a new window with
that URL.
After the function declaration comes an opening curly bracket ({). You’ll see the
closing curly bracket on the last line. Everything in between these curly brackets is
the code that will run.
The two lines of code are actually one line that runs longer than the printable area
of this page. The line starts by creating a newvariable. A variable is a container, a
place to put things. In this case we’re putting the window-opening code into the
variable calledaWindow. More commonly, variables are used to store information
about the current state of the page or the user environment.
Free download pdf