Learn Javascript
Event Handlers
Join the Discussion
More of this Tutorial
Related Terms
Introduction
So far we have looked at running Javascript either before or during the loading of your web page. Often you will want Javascript code to run once the page has finished loading or even afterwards in response to some action by the person viewing the page.
The means that Javascript provides to allow Javascript code to be triggered once the page has loaded is to attach event handlers to those parts of your page that are to act as triggers for the Javascript that you want to have run.
Types of Event Handler
There are a number of different types of event handler that will be triggered by different events. The types of events that can trigger Javascripts attached to event handlers include:
- mouse actions
- keyboard actions
- actions on form fields (regardless of how caused)
- when the page is first loaded or unloaded
- after a specified time has passed
You can also set up events that will be triggered by any part of your page without having to attach the event to each part of the page separately by making global event handler).
Many of the event handlers are paired with one being triggered by a certain action (eg. mouseover) and another being triggered by the reverse action (eg. mouseout). By attaching both of a pair of event handlers to the same object on the page you can set up one to perform a specific action and the other to perform the reverse action returning the page to its original appearance.
Attaching Event Handlers
The simplest way to attach event handlers into your page is to insert them directly as attributes on the HTML tags of the object that will trigger them. To trigger an event handler so attached requires that the particular action that the event handler recognises be performed in relation to the object to which it is attached.
In general event handlers will be attached into a tag using code similar to the following (substituting the appropriate event name and function to run for the code in italics):
Note that this is not the best way of attaching event handlers but it is the simplest and most commonly used. When you become more familiar with Javascript you will want to move the event handlers out of your HTML into the external Javascript file along with the rest of your Javascript code.
What's Next
Event handlers are what enables you to attach Javascript to your page that will allow your page to interact with your visitors. Over the next few tutorials we will look at the various event handlers and how to trigger them.

