Weeb tutorials feedback Powered by

Where and how to write Javascript code.

How to write your code

First of all, there are two ways to write your Javascript code. Lets have a look at these options.

The first is by embedding the code in your HTML document. We do this by using the opening and closing script tags, defining the script type & typing our code.

We seen an example of this in our introduction to Javascript article.

The second method is to write our code in an external file. This benefit of this method is that we can run the same code on multiple pages if necessary. Thus saving ourselves from repetitive strain injury!

How to reference an external Javascript file:

<script type="text/javascript" src="javascript.js" </script>

 

Please note, when writing code in an external file you do not need to use the opening and closing script tags. Also, the file must be saved with a .js file extension.

Where to write your code

You can place your code in either the head section, or the body section of your HTML page. A couple of things to consider:

Upon loading a page, a web browser will automatically execute all javascript code. Sometimes, this is not what we require.

For example, lets say we want a message to appear when a user clicks a certain button.

Well in a scenario like this we would need to place our code inside a function. An example follows:

<head>

<script type="text/javascript">

function showMessage()

{

alert("You have just clicked the button!")

}

</script>

<body>

<input type="button" onclick="showMessage()" value="Click me!"/>

</body>

Scripts such as the above, that is, scripts which are to be executed when called should always be placed in the head section.

Other scripts, which are to be executed when the page loads should be placed in the body section.

Things to remember

  1. You can either embed your code directly into a HTML page, or write it in an external .js file.
  2. An external file should not contain the script tags.
  3. If you don't want your code to be executed when the page loads, place it in a function. Place this function in the head section.
  4. Don't worry too much about functions at the minute. We will cover them later. If you wish to know more know you should check the related links section to the right.
This is the old version of our site. To visit the new version click the following link: New site