/ BTEC National Diploma Level 3 Ken Wake – September 2007 / Version 1.0 Revised 16/09/07
Number 2-07-02

Creating your first Script –

In this exercise we are going to create a simple script to change the background colour of our page when it loads into the browser.

Firstly – let me emphasise that in normal practice we would never do this, our basic page styling is normally handled by the stylesheet, this script is purely to demonstrate linkage and deployment of javascript.

The first thing we will do is set up our javascript environment.

1.  Create a folder called javascript practice

2.  Create a subfolder in the javascript practice folder called js

3.  Create a subfolder in the javascript practice folder called styles

4.  Create an xhtml file called embedded-script.html and save it in the javascript practice folder

5.  Create a stylesheet called styles.css and save it in the styles folder

6.  Create a javascript file called embedded-script.js and save it in the js folder

The next thing we will do is establish our links

In the document called embedded-script.html, add the following lines IN THE HEAD

<link rel=”stylesheet” href=”styles/styles.css” type=”text/css” />

<script language=”javascript” type=”text/javascript” src=”js/embedded-script.js”</script>

The first line, as you know already, links the stylesheet to the xhtml document.

The second line, links the javascript file so it is imported when the page loads.

Now it is time to write your first javascript file

In the file called embedded-script.js, write the following lines:

document.bgColor ="Red";

Load the XHTML document into your browser, if the background turns red then all is well, if it doesn’t then you will need to check your code to make sure that all documents are linked properly.

The most common errors in all Javascript deployments are mis-spellings or bad naming conventions such as using uppercase characters or gaps in file names etc. As a matter of good practice, NEVER use uppercase letters in filenames and NEVER leave gaps… ie call a file “my-javascript.html” not “my javascript.html”.