Sticktime Publishing


The JavaScript Book

JavaScript adds dynamic properties to a webpage. Without JavaScript webpages are largely static and unchangeable. JavaScript adds dynamicism by acting on single HTML elements or classes of HTML elements within an HTML document. If you don’t know what an HTML element is you are not ready for this volume and you need to study the HTML Book, this book’s sister volume.


Most books about programing begin with a “helloworld” example but we begin with three, as there are three places JavaScript script can be placed in the context of an HTML document.

The code below shows JavaScript embedded in the HTML’s body:
<!-- Minimal JavaScript Program in <body> -->

<!doctype html>
<html>
<head>
	<title>Minimal JavaScript in <body></title>
</head>
<body>
	<script>
		document.write( "<p>Hello World!" );
	</script>
</body>
</html>
The code below shows JavaScript embedded in the HTML’s header:
<!-- Minimal JavaScript Program in <head> -->

<!doctype html>
<html>
<head>
	<title>Minimal JavaScript Program in <head></title>
	<script>
		function HelloWorld()
		{
			document.write( "<p>Hello World!" );
		}
	</script>
</head>
<body>
	<script>
		HelloWorld();
	</script>
</body>
</html>
Here we place the JavaScript into a separate ‘.js’ file:

Here is the referring HTML file:

<!-- Minimal JavaScript Program in External .js File -->

<!doctype html>
<html>
<head>
	<title>Minimal JavaScript Program in External .js File</title>
	<script src="external.js"></script>
</head>
<body>
	<script>
		HelloWorld();
	</script>
</body>
</html>

And here is the small “HelloWorld.js” file that the above HTML file refers to:

// Minimal JavaScript Program External .js File

function HelloWorld()
{
	document.write( "<p>Hello World!" );
}