O'Reilly logo

Web Design in a Nutshell, 2nd Edition by Jennifer Niederst Robbins

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

JavaScript Basics

JavaScript code is usually placed directly in an HTML document. The code can go in either the head or the body, and there can be numerous scripts in a single HTML document. Here’s the syntax:

<SCRIPT LANGUAGE="JavaScript"> 
<!--
script goes here 
//-->
</SCRIPT>

The <script> tags define the boundaries of the script and set the scripting language to JavaScript. The language attribute is necessary to distinguish JavaScript from other scripting languages, like VBScript, that can also be embedded in web pages. Finally, HTML comments surround the script to hide the code from really old browsers that don’t understand the <script> tag. Otherwise, those browsers would just display the code like preformatted text, which isn’t very pretty.

Functions

There are two parts to most JavaScript applications: the functions that tell the browser what to do, and actual uses of these functions. Let’s take the example of a simple web page that displays a linked document in a second window:

<HTML> 
<HEAD>
<SCRIPT LANGUAGE="JavaScript"> 
<!--
function openWin(URL) { 
    aWindow = window.open(URL,"composerwindow","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, called ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required