Categories:

Event handling in the DOM

Event handling has been part of JavaScript since the language's inception. As described in our event handler tutorial, they refer to specific, user imitated actions within the webpage, such as the moving of your mouse over a link, the clicking on a link, or submission of a form. Thanks to event handling, our scripts are more interactive and are able to perform certain actions depending on the user's.

The DOM of modern web browsers such as IE5+, NS6+, and Firefox provide expanded methods and flexibility (relative to older browsers) for capturing events. In this tutorial, we explore event handling in the DOM, and the differing support for it in IE5+ and NS6+/Firefox.

The 2 traditional ways of assigning event handlers

Let's first review (for most of us, at least) the 2 common and conventional ways of setting up an event handler- via HTML, or scripting. In both cases, a function or code is attached at the end, which is executed when the handler detects the specified event.

1) Via HTML, using attributes

We can define an event handler directly inside the relevant HTML tag, by embedding it as a attribute. A piece of JavaScript is also included to tell the browser to perform something when the event occurs. For example,

<a href="http://freewarejava.com" onMouseover="window.status='Click here for Java applets';return true" onMouseout="window.status=''">Freewarejava.com</a>

Demo:

Freewarejava.com

Here the event handler (onMouseover) is directly added inside the desired element (A), along with the JavaScript to execute.

2) Via scripting

You can also assign and set up event handlers to elements using scripting, and inside your script . This allows for the event handlers to be dynamically set up, without having to mess around with the HTML codes on the page.

When setting up event handlers for an element directly inside your script, the code to execute for the events must be defined inside a function. Just look at the below, which does the same thing as above, but with the event handler defined using scripting:

<a ID="test" href="http://freewarejava.com">Freewarejava.com</a> 

<script type="text/javascript"> 

function changestatus(){
window.status="Click here for Java applets"
return true
} 

function changebackstatus(){
window.status=''
} 

document.getElementById("test").onmouseover=changestatus
document.getElementById("test").onmouseout=changebackstatus 

</script>

Notice how we attached the two functions to execute for the two events- the function names without the parenthesis. This is called a reference call to the function. When assigning a function to an event via scripting, always use a function call. If you were to include the parenthesis of the function inside the definition, an error will be generated.