HTML Markup | JavaScript | Java | Home & Links

Tutorial 4 - Events

JavaScript is interactive because it is event driven (ie. it reacts to user or system activities). This tutorial describes events and how they are initiated with handlers and listeners. The list of available events is documented here.

Event Handlers

Events are actions that occur because of user interaction. Using the car analogy given previously one possible event is pressing the parking brake pedal which would use the applyParkingBrake() method and perhaps others such as turnBrakeIndicatorOn() and turnRunningLightsOff(). In computing, user events (like moving the mouse) or system events (like a file completing loading) are common occurrences. The events list describes available events.

Event handlers are functions that initiate processes such as checking for valid data after events occur. The most common method of associating an event to an event handler is to treat the event as an HTML attribute for the appropriate element. Note that any element, not just form controls can have associated events. To enable event handling from an HTML attribute use one of these function calls:

eventName="functionName(parameterList);return true;"
    This format forces a true result to be passed to the eventName.
eventName="return functionName(parameterList);"
    This format allows a function to return a true/false indicator.
    This can be used with validation handlers to react to bad input.
eventName="functionName(parameterList);"
    The result passed is unpredictable.

For example: <body onload="startUpStuff()>" would call startUpStuff() as soon as the page was loaded.
Another example is: <button onclick="transfer(a,b);return true;">Transfer Now!</button> This time the function would be called with a button onclick. Note that the string between the event attribute quotes is a list of statements. If there are more than a couple of statements it is good programming practice to call a single function whose task is to sequence those statements. And the code is much more readable too!

Event Listeners

Event listeners are event/event handler associations that are defined within JavaScript itself. They let the application react to a user initiated event immediately. They also can be applied to any element while the attribute method is restricted to form controls. For example resizing a window may require repositioning of some elements.

window.onresize=HandlerName;

In this example HandlerName is a pointer to a handler function that will be called on each window resizing event. Note that there is no parameter brackets for the event listener function pointer. The initiating event object is passed to the function differently based on the browser! FireFox gets a passed parameter while MSIE uses the window.event object. The following shows how to make a handler function browser-transparent by object sensing.

function HandlerName(e){
e=e||window.event; // browser fudge
... }

Beware: The onresize event in some browsers only applies to a window and not to an object. It sometimes helps to implement an onFocus event listener as one natural user reaction is to click on any out-of-sorts display before clicking on the refresh icon.

An example of acting on each keystroke by using an event listener and the event object is:

document.onkeydown=keyHit;// register key pressed event
upArrow=38;dnArrow=40; // names for important keys
function keyHit(evt){
  thiskey=window.event.keyCode;
  if(thiskey==upArrow){alterSelection(-1);}
  if(thiskey==dnArrow){alterSelection(+1);}
  }

The evt object can be tested if you need to restrict keystrokes to specific zones or elements. You can use an alert(thiskey) method to show the specific keyCode. It helps to make a name synonym for any keyCode that is being used such as pound or percent.

The Events List

Note: Not all user events have event handlers. Important ones missing are onZoom and onTextSized. Also the onResize event only reacts to window resizing, not object resizing in both Firefox and Opera.

Note: When used as an attribute, an event handler must be typed in lowercase only (eg. onclick) to meet HTML specifications! Most, but not all of the following user event handlers can be included as attributes on any element.

Interface Event Handlers:

Event Name Handler Executes When
onBlur focus is lost (ie. changed or blurred) to a new element
onFocus object gains focus. aka anti-blur!
onLoad window, complete frame or image(s) finishes loading
onResize a window or object(MSIE only) is resized
onScroll window scrolled with scrollbar or mousewheel
onUnload window or all windows in a frame have been exited
onAbort image load has been abandoned by clicking the STOP icon
onError window or image fails to load

Key Event Handlers:

Event Name Handler Executes When
onHelp GUI F1 key pressed. Used to override browser Help
onKeydown alphanumeric key is pressed
onKeypress alphanumeric key is fully pressed/released
onKeyup alphanumeric key is released
onStop GUI STOP key is pressed or user leaves page

Mouse Event Handlers:

Event Name Handler Executes When
onClick left mouse clicks on element. Can be stopped if executing
procedure (such as validation) returns a false signal
onContextmenu right mouse button clicked
onDblclick mouse button is double-clicked
onMousedown either mouse button is clicked
onMousemove mouse is moved
onMouseOut cursor leaves a link or area
onMouseOver cursor enters a link or area

Form Event Handlers:

Event Name Handler Executes When
onChange last element has been changed before focus change
onReset the reset button is clicked
onSelect some text is highlighted in input, password or textarea
onSubmit Executes after return key is pressed or submit button is clicked.
Allows bailout similar to the onclick event. Failure in validation
routine is the most common reason for bailout

Example: Time On Page

This example illustrates how one can time how long a viewer remains on a page. The events onLoad and onUnload are used to flag the activities. The personIn function records the start time. The personOut function records the stop time, computes the difference and shows the result to the reader. The result could also be stored in a cookie!

<script type="text/javascript">
function personIn(){enter=new Date();}
function personOut(){
  exit=new Date();
  timeDif=(exit.getTime()-enter.getTime())/1000;
  timeDif=Math.round(timeDif);
  alert("You've only been on this page for: "+timeDif+" seconds!!");
}
</script>
. . .
<body onLoad="personIn()" onUnload="personOut()">
<h1>Timing This Page Now!</h1>


JR's HomePage | Comments [jstutor4.htm:2014 07 11]