Home : Internet : JavaScript : Basics

JavaScript Basics

To use JavaScript in a web page, simply insert the JavaScript into the HTML at the appropriate place (more on exact placement later). JavaScript is usually placed within identifying tags like so:

<script language="javascript" type="text/javascript">
// The JavaScript code goes here
</script>

When the page is opened in a browser, the HTML is rendered as normal and the JavaScript is executed as it is found. Here is a simple example of a complete HTML page containing some JavaScript:

<html><head><title>Simple Page</title></head><body>
<p><font color="maroon">The next line is generated by JavaScript:<br>

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

</font></p>
</body></html>

This will be displayed as:

The next line is generated by JavaScript:
Hello World!

Let's break down this example.

As you can see , JavaScript can be dropped in anywhere to add content to the page. JavaScript output can also include HTML tags, like so:

<script language="javascript" type="text/javascript">
	document.write('JavaScript can output HTML such as <b>bold text</b>,<i>italics</i>, etc');
</script>

At this stage you might be wondering why you would bother using JavaScript to create page content instead of just using plain old HTML. The answer is that for normal static HTML there is no point, but JavaScript provides a whole range of interactive options so the HTML can be modified dynamically. For example, a user could enter their name into a dialogue window and JavaScript could include their name in the HTML.

Remember, writing HTML to the page is only one part of JavaScript's capabilities. JavaScript can do many things such as create new windows, control frames, request information from the user, and much more. At this stage though, we will concentrate on creating HTML to enhance the web page.