Events And JavaScript: Part 1 - Event Handling

By HTMLGoodies Staff

written by Jon Perry

We can see this differentiation of objects and events in an example.

The object may be a bus, traveling around its route. The events that are significant for the bus are:

    Passenger boards
    Passenger pays
    Passenger leaves
    Bus arrives at destination

The important features of the model are that the bus can take any route and still use the same events, and the same events apply to any bus and any combination of passengers.

Computer programs use this idea. We can model most situations with the basic Object-Orientated Event-Driven computer programming idiom.

HTML and JavaScript provide an excellent example of this model. HTML provides the objects, and JavaScript provides the event handling capability.

This article will introduce the idea of attaching events to HTML elements, and writing code to provide greater finesse within our web documents.

HTML Events

Not all events are significant to a program. We can simplify situations to determine which events are significant, and which events we can leave out. For example, a leaf hitting the bus is an event, but is not a significant event if we wish to model the cost effectiveness of the bus route.

As we know, HTML provides elements to allow us to create web documents. We can fill these elements with our own data and display unique web documents. We can position the elements with careful planning, and create aesthetic web sites.

This is the object-orientated part of web documents. DHTML, or Dynamic HTML supplies the event-driven side of things.

To begin using DHTML, and therefore event-driven HTML, we need to look at what events happen to our web document.

There are over 50 events in all. Some can happen to a lot of HTML elements, some only happen to specific HTML elements.

For example, moving the mouse pointer and clicking the mouse buttons create the following events:

· onmousedown
· onmousemove
· onmouseout
· onmouseover
· onmouseup
· onclick
· ondblclick

The event happens to the object. So, if the mouse pointer is over an image, say Image1, and we click it, we create an (object, event) pair, in this case (Image1, onclick).

If we move the mouse into a select box, Select1, we create (Select1, onmouseover), and so on.

We need technical definitions of the events to be able to appreciate what is actually happening.

Mouse Event     Description
onmousedown     A mouse button has been pressed
onmousemove     The mouse has been moved
onmouseout     The mouse pointer has left an element
onmouseover     The mouse pointer has entered an element
onmouseup     A mouse button has been released
onclick     A mouse button has been clicked
ondblclick     A mouse button has been double-clicked (clicked twice rapidly)

The idea behind this is to represent all the possibilities we may encounter in computer events. This doesn't allow for events like the mouse is dirty, or the mouse is upside-down - these are not relevant.

You may also notice that some actions will fire two events. Moving the mouse into or out of an element will fire both a mousemove event and a mouseover (or mouseout) event. Clicking a mouse button fires a mousedown, click and mouseup events.

The other user-type event is generated by the keyboard.

Keyboard Event     Description
onkeydown     A key has been pressed
onkeypress     onkeydown followed by onkeyup
onkeyup     A key has been released

Remaining events have a more conceptual taste. There are a few too many to list here, but they are well documented. Commonly used events include:

Event     Description
onblur     An element loses focus
onerror     An error occurs
onfocus     An element gains focus
onload     The document has completely loaded
onreset     A form reset command is issued
onscroll     The document is scrolled
onselect     The selection of element has changed
onsubmit     A form submit command is issued

We will look at the onfocus event at the end of this article, which may help your understanding of the subtler events.
Attaching Events to HTML elements

The first thing you need to know is that when onblur or onmousover or any other event is used within your HTML page, it is commonly referred to as an event handler.

Now we need to write some JavaScript to enhance the current functionality of the element, and this is where it can get complicated.

We all know what a typical HTML element looks like, and hopefully we know what an HTML element with the STYLE attribute looks like.

As a re-cap, an HTML element is:

<P>Hello from the 60's</P>

and with style:

<P STYLE="position:absolute;top:10;left:10;color:black">Hello from the 60's</P>

To attach the event handler of our choice to this <P> element, we need to notify the element of the type of event to watch out for, and also we have to tell the element what to do when it does receive the event.

To create the psychedelic 60's effect I have in mind, we need to monitor for the onmousemove event. The JavaScript to create this code is fairly simple, we change the color to a random one every time the mouse pointer moves over the <P> element.

The whole code for the <P> element therefore looks like:

<P onmousemove="style.color=Math.floor(Math.random()*16777215);" STYLE="position:absolute;top:10;left:10;color:black">Hello from the 60's</P>

Placed in an HTML document, we get:

<TITLE>Hello from the 60's</TITLE>
<P onmousemove="style.color=Math.floor(Math.random()*16777216);" STYLE="position:absolute;top:10;left:10;color:black">Hello from the 60's</P>

When we move the mouse pointer over the text, we get a very psychedelic effect. Note that the mouse pointer must be moved, it's mere presence over the text is not an event.

The strange number, 16777216, is the total number of colors we get. We can use any of 256 red shades, 256 green shades and 256 blue shades, so the total is 256^3 = 16777216.

This is slightly obscured by the fact that the first number is 0, and so we only want the range (0 - 16777215). This is created by the Math.floor() method with the Math.random() method. Math.random() returns a number between greater than or equal to zero, but less than 1. When we floor the random function, we will never get 16777216, but will get 0 - 16777215.
Other Event Handling Techniques

This is not the only method we have for attaching events to elements, and nor is it the only method we have for implementing JavaScript.

Function Calls

We could house the JavaScript in a function, and so the 60's program becomes:

<TITLE>Hello from the 60's Again</TITLE>
function randomcolor() {
<P onmousemove="randomcolor();" STYLE="position:absolute;top:10;left:10;color:black">Hello from the 60's</P>
<P onmousemove="randomcolor();" STYLE="position:absolute;top:50;left:20;color:black">Hello from the 70's</P>

Now our event handler calls the randomcolor() function.

The randomcolor() function is slightly more complicated the method used before. It makes use of the Event object, which I will cover in detail in a later article.

One of the properties of the event object is the srcElement property, which contains the element that initiated the event.

We can use this style of event handler to make our code terser and more efficient. We can even use the same function twice, and independently.

Attaching Events

We also have several different techniques for attaching the event to an object. We have met one of them already, which is direct attachment of the event to an object.

We can also indirectly attach the event to the object. We can achieve the same event handling effect as before from within a script tag.

<TITLE>Hello from the 60's Part 3</TITLE>
<P ID="sixties" STYLE="position:absolute;top:10;left:10;color:black">Hello from the 60's</P>
function sixties.onmousemove() {

This code is fairly stylish, but causes a few more problems. As the script contains a reference to the sixties object, this object must have been created before the script can use it. If we place the <SCRIPT> element where we usually do, inside the <HEAD> element, we get an error message, because the sixties object does not yet exist. So we must place if after the sixties object has been created.

We can also create little script elements, which we assign to an object.

<TITLE>Hello from the 60's IV</TITLE>
<P ID="sixties" STYLE="position:absolute;top:10;left:10;color:black">Hello from the 60's</P>
<SCRIPT FOR="sixties" EVENT="onmousemove">

To finish the article, we shall look at one of the more conceptual events, the focus event.
Focus Event

The focus event occurs when an element is given the focus. Focus is the ability to receive further events, and is most commonly used with forms. When we click between form elements, we transfer the focus from one element to another, which means that we can now enter text into the newly focused text box.

We may wish to add extra functionality to this event, for example, we may want to have a small status bar message displaying the current question.

This would involve capturing the onfocus event, and handling it.

<TITLE>Form Focus</TITLE>
function question() {
<FORM ID="mainform">
<LABEL ID="labelname" FOR="name">
<INPUT TYPE="TEXT" NAME="name" onfocus="question();">
Full Name</LABEL>
<LABEL ID="labelemail" FOR="email">
<INPUT TYPE="TEXT" NAME="email" onfocus="question();">
Email Address</LABEL>

This program captures and handles the onfocus event. The event occurs when either of the form elements is given the focus, and the situation is reinforced by the question being repeated in the status bar.

We capture the event in the <INPUT> element, and tell the computer to call the question() function.

The question() function uses a esoteric string of methods and properties to get the information we want as efficiently as possible.

The explanation lies within the innerText property.

InnerText retrieves the text inside an element. Note that the element must have a required closing tag, e.g. <P> or <SPAN>. <INPUT> only has an optional closing tag, and therefore doesn't ever have any innerText.


<P ID="title">Events and Event Handling</P>




Events and Event Handling

When the onfocus event is captured, the Event object gets loaded with all the relevant data. We can therefore ask the event object what is the name of the element that fired this event.

With careful planning, we can assign labels to each form text box, and give each label a name consisting of the prefix 'label' and the name of the element it is associated with.


This changes the status bar text to the innerText of the label that is associated with the element that fired this event.

Hopefully by now we have a grasp of events and event handling. The more we understand events, the better our programs become.

This article originally appeared on WebDevelopersJournal.com.

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
Thanks for your registration, follow us on our social networks to keep up-to-date