Basic Javascript (DHTML) Tutorial

Javascript is a scripting language whose source code is downloaded along with the HTML code of your page, and is executed by the browser once the page has loaded. Javascript has syntax similar to that of Java (or C), but is easier to program. Javascript is wired up so that it has full programmatic access to all of the HTML tags within your page. You can read, write, change and delete tags using Javascript functions to produce an almost limitless scope of interesting effects.

This JavaScript tutorial is indended to give the reader a quick introduction to the basics of Javascript which then lead us on to producing more interesting Javascript applications, such as menus and form validation - two of the most common uses of Javascript.

Where do JavaScripts go?

Like CSS, Javascript may be included inline to your HTML page using a special container tag, in this case the <script> tag.

The script tag should to be told which language to use using the type="text/javascript" attribute. There are other scripting languages that browsers can use, although JavaScript is the most widely used.

You may also include an external JavaScript file by adding a src attribute to the <script> tag. This is useful if you want to have several pages of your site use the same script.

Example 1 - Hello World

Here's a first classic "Hello, World" example which displays a message box when the page loads.

<script type="text/javascript">
alert("Hello, World");
</script>
View Source Run Example

In this example we use the alert() function to display a message box. The alert function takes a text string as an argument for what to display in the message box.

The following are some code snippets that build on the first basic example, showing you more JavaScript language features and techniques.

Example 2 - Using prompt() instead of alert()

Instead of a message box, we can use a prompt() function to ask the user for some input.

<script type="text/javascript">
var colour = prompt("What is your favourite colour?", "");
if (colour != "") {
alert("Your favourite colour is " + colour);
}
</script>
View Source Run Example

The prompt function displays an input box which returns a variable containing the user's value. If the user clicks cancel or doesn't enter the variable, a empty text string is returned. We use an if statement to see if the variable contains any data, and if it does, we notify the user of their choice once again using the alert() function.

Note For Existing Programmers
JavaScript is not strongly typed. All variables are typed as a var

For example:
var tag = document.getElementById(?box?);
var string = ?Hello, World?;
var number = 123;

But:
Javascript is CaSe-sensitive, so be careful how you type variable and function names.

Example 3 - Changing Styles with JavaScript

Our examples have been quite dry so far - let's use JavaScript to start changing some properties on the page. In this example we'll extend the previous example to changes the page's background to the user's favourite colour.

<script type="text/javascript">
var colour = prompt("What is your favourite colour?");
if (colour != "") {
document.body.style.backgroundColor = colour;
}
</script>
View Source Run Example

The code is pretty straighforward. We can get an object reference to the body tag (whose background property we'll change) using document.body. Once we've got the body tag, we can simply change a member of its style object, in this case the backgroundColor property.

You'll notice that for almost every property we can specify in CSS or via HTML attributes, there is an equivalent object property in JavaScript. The Document Object Model (DOM) is a standardised model which defines how we can access all of these attributes from JavaScript functions.

For example, the CSS Class attribute (class="cssClass") of a tag is equivalent to the object.className property. We'll have a go at changing the class of an object in a later example.

Example 4 - JavaScript Functions

Each time we've created a JavaScript that executes immediately, and only once. What happens if we want to run our code at a different time - or more than once. This time we'll update our previous example to use JavaScript functions

<script type="text/javascript">

function chooseColour() {
    var colour = prompt("What is your favourite colour?");
    if (colour != "") {
        document.body.style.backgroundColor = colour;
    }
}

</script>

<a href="javascript: chooseColour();">Choose Colour</a>

View Source Run Example

This time we've enclosed our JavaScript within a function { }. Like any sub routine in a programming language, this function won't now run until it's called. We prefix the href with "javascript: " and the name of the function. Now that we've used a function, we can call it over and over again.

Example 5 - Changing CSS Class Dynamically

This time we'll move on and change the CSS class instead. We'll also change the property of something other than the body tag, which is slightly more difficult.


<style>
.class1 {
    background-color: red;
    color: white;
    width: 100px; height: 100px;
    border: 1px solid black; text-align: center;
}
.class2 {
    background-color: white;
    color: red;
    width: 100px; height: 100px;
    border: 1px solid black; text-align: center;
}
</style>

<div class="class1" id="box" onClick="toggle();">
Click Me!
</div>

<script language="JavaScript">
function toggle() {

    var obj = document.getElementById("box");

    if (obj.className == "class1") {
        obj.className = "class2";
    } else {
        obj.className = "class1";
    }
}
</script>

View Source Run Example

We start off by defining two distinct CSS classes. The first has a red background and the second a white background. Secondly we define a div tag define the onClick attribute which allows us to call a function every time the box is clicked on, and set a unique identifier in the tag's id attribute.

The JavaScript function first gets a reference to the tag using the document.getElementById() function which (unsurprisingly) gets a reference to the object with a particular id. The function then checks the tag's className attribute, and swaps it over.

Example 6 - Using the this statement

We've seen how JavaScript functions allow us to reuse code. The code above, however, only works for one box as the function itself has the name of the object to change "hardwired" into it. What would be better is to pass the object to change to the function, which can then do the work for many different objects.

This time we'll try a different event caller - the onMouseOver and onMouseOut attributes.


<style>
.class1 {
    background-color: red;
    color: white;
    width: 100px; height: 100px;
    border: 1px solid black; text-align: center;
}
.class2 {
    background-color: white;
    color: red;
    width: 100px; height: 100px;
    border: 1px solid black; text-align: center;
}

<div class="class1" 
    onMouseOver="over(this);" onMouseOut="out(this);">
Box 1
</div>

<div class="class1" 
    onMouseOver="over(this);" onMouseOut="out(this);">
Box 2
</div>

</style>

<script language="JavaScript">
function over(obj) {
    obj.className = "class2";
}
function out(obj) {
    obj.className = "class1";
}
</script>

View Source Run Example

This time we're using two functions - one to highlight the box and one to de-highlight the box. We don't need to use the document.getElementById() function this time - we get the object passed to the function directly. To do so, we use the this keyword, which allows the tag to send a reference to itself as an argument to the function.

Example 7 - Changing HTML Dynamically

We'll take a break from the className property for now, and play with a different property - the innerHTML property. The innerHTML property allows us to manipulate the code within a tag.

For example:
The innerHTML of the following <body> tag:
<body><h1>My Page</h1></body>
Would be: "<h1>My Page</h1>"


<script language="JavaScript">
var quotes = new Array();
quotes[0] = "'Only two things are infinite...'.Carriage Return
    <br /><small>Albert Einstein</small>";
quotes[1] = "'Do, or do not. There is no 'try''.Carriage Return
    <br /><small>Yoda</small>";
quotes[2] = "'Black holes are where God divided by zero.'Carriage Return
    <br /><small>Steven Wright</small>";

var currentQuote = 0;

function getQuote() {
    document.getElementById("box").innerHTML = Carriage Return
    quotes[currentQuote];
    currentQuote++;
    if (currentQuote > quotes.length - 1) currentQuote = 0;
}
</script>

<div id="box" onClick="getQuote();"
>CLICK ME FOR A QUOTE!
</div>


View Source Run Example

Here our JavaScript code defines an array. C/Java programmers: don't worry about the size of the array - Javascript expands the array size automatically. We define our array and currentQuote variables outside of the function allowing them to act as global variables. The getQuote function cycles the innerHTML property of the box tag through the different values stored in the array.

You'll notice that the innerHTML may contain further HTML inside it.

Example 8 - Writing HTML

As well as manipulating existing HTML, we can write new HTML. Once that has been created, we can then manipulate it in the same way as any other code already on the page.

Writing html is simple, using the document.write() function. In the next tutorial we'll use is extensively to create JavaScript menus.

Back to tutorials