Scripts: Javascript

How To - The Basics

There are a number of ways in which you can apply JavaScripts, the following describes the fundamentals. The three main ways in which you can insert JavaScripts into a page:

External script file

One way is to link to another file which contains the Javascript code (a *.js file). This means that the script can be used by a number of web pages and you only need to modify it once to effect all the pages (makes updating simpler).

<SCRIPT Language="JavaScript" SRC="scripts.js"></SCRIPT>

The contents of the *.js file need to be laid out like this:

<!--

Script contents

//-->

Embedded Scripts

Another way is to insert javascript dirrectly into the web page. Generally, this is done between the <HEAD></HEAD> anchors of the page, but it can also be placed anywhere in the pages body.

 

<SCRIPT Language="JavaScript">
<!--

Script contents

//-->
</SCRIPT>

Note: It's good practice to add 'comments' as you go so that next time you look at/tweak the script you know what you've done. Each comment describes what each part of the script is doing.

<!--

// This is a comment, anything after the forward slashes is ignored by the browser.

//-->

Direct Links

The final way to insert a javascript into a web page is to put it dirrectly into a link (I prefer using the second variation).

<A HREF="javascript:window.print();">print page</A>
<A HREF="javascript:;" onClick="window.print();">print page</A>

Script Triggers: Event Handlers

You can also change the 'event' that triggers the javascript, e.g. the page loads (onLoad) or the mouse moves over the link (onMouseOver). Click here for a full list of all the event handlers:

<IMG="image.gif" onMouserOver="plop();">
<BODY onLoad="plop();">