Lesson 2: Functions

A function is an extremely valuable tool used in JavaScript that saves a lot of time. Before we dive into the workings of functions first we we will have to define one of the fundamentals of JavaScript.

Event Handlers

An event handler is a set of instructions that tell the browser what to do when a particular event occurst. For example, this may be a button. Event handlers are what JavaScript is all about. The ability to add interactivity to your web pages is one of JavaScript's most important features.

Now you are ready for your first function and event handler...

The first thing you will do is place the function in the [HEAD] section of the document. This covers the whole document like this:

function alerUser ( )
{alert ("You have just received 50 IQ points")}

The empty brackets ( ) on the fourth line mean that we have not stated a parameter. The next lesson will create a function with a parameter. For now, look at what is between the braces on the fifth line { } . This is the action that takes place when the function is alertUser is called upon from anywhere in the document.

If you're wondering what this function does it simply tells the computer to send an alert box stating that You have just received 50 IQ points! . But how can the user trigger this event you ask? Simple, by adding an object like a BUTTON. As long as the button calls the function you will see the alert box. Now we will show you how to create the button.

In the [BODY] of the document you will add a section called [FORM] and create a button that calls the function alertUser ( ) :

[INPUT TYPE="button" NAME="oneButton" VALUE="A gift from us" onClick="alertUser ( )"]

The button called A gift from us automatically calls upon the function alertUser go ahead and click on the button.

To proceed to the next lesson click here Lesson 3