Tutorials

Learn web design and programming with our free video and text tutorials.

External Javascript Tutorial

Javascript allows you to run the same javascript on more than one page at time, while only having to write the javascript code only once, in a seperate file. This is similar to using external style sheets in CSS.

To place javascript into an external javascript file, first create a blank file and give it a ".js" extension. For this tutorial, give the file that will contain the external javascript the name "myjavascript.js".

For this tutorial, we will be displaying the date and local time on each page that references the javascript code that is located in the external javascript file. The date and time below is a working example of the javascript code in action.

Now enter the javascript code below into the blank file, however, do not include the enclosing <script> tags in the file.

cDate = new Date();
document.write("The date and time is: " + cDate.toLocaleString());

The code that is used to include the external javascript into your (X)HTML file is:

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

Now enter the code above into your (X)HTML file and name it "jspractice.html".

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>WebDevelopmentTutorials.com</title>
</head>
<body>

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

</body>
</html>

Now view your jspractice.html page. It should display the current date and local time.