Getting Started with JavaScript

JavaScript can be inserted into an HTML page using opening and closing script tags, <script></script>. These can be placed either in the header or body sections of an HTML page. Below is an example of a JavaScript function defined in the header section of the page, with it being called from a button found in the body. A function contains a block of code that performs a specific task and can be called using its name.

<!DOCTYPE html>
<html>
<head>
<script language="javascript" type="text/javascript">
function helloFunction() {
     document.getElementById("helloText").innerHTML = "Hello world";
}
</script>
</head>

<body>

     <h1>JavaScript Example</h1>

     <p id="helloText">Click the button to change the text.</p>

     <button type="button" onclick="helloFunction()">Click</button>

</body>
</html>

The above example uses a button to call a function, 'helloFunction', which is defined in the header of the page. All the function does is to change the text of the paragraph to 'Hello world'. The function uses the id assigned to the paragraph, in this case 'helloText', to pinpoint the correct paragraph to change. In this example, there is only one paragraph, but JavaScript would still need to use the id in order to make the change.

It is common practice when using functions, like the one in the above example, to place them in the header and call them from the body.

If there are a number of functions to be defined on a particular page, or, the same functions are to be used across multiple pages then they can be placed in an external file with a '.js' extension. This file is then referenced in the header section of the web page so that the functions can be used. Note that when the JavaScript is placed in an external file, the script tags are not needed. The JavaScript file is included in the header as follows.

<head>
<script src="myFunctions.js"></script>
</head>

If the JavaScript file does not reside in the same folder as the HTML page, then the path would need to precede the name. JavaScript can also be included in the body of a page in a similar fashion.

Code Commenting

As with any programming or scripting language, it is good practice to include comments to make it easier to understand your code. You can either use single or multi-line comments as shown below.

<script language="javascript" type="text/javascript">

     // This is a single line comment.

     /* This
        is
        a
        multi
        line
        comment */

</script>

To handle browsers that don't support JavaScript, or where support for it is disabled, it is also good practice to wrap your JavaScript code in HTML comments.

<script language="javascript" type="text/javascript">
<!--
   document.write("Hello World!")
//-->
</script>