HTML Markup | JavaScript | Java | Home & Links

Tutorial 4 - Events

JavaScript is highly interactive because it is event driven (ie. it reacts to user or system activities). This tutorial describes event handling as well as many useful effects using events.

Events and 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 the 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 call syntaxes:

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()>"

The preceding line would call the function 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 receives a passed parameter while MSIE uses the window.event object. The following shows how to make your 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.

Beware: The zoom (Opera/SlimBrowser) and font resize (FireFox/MSIE) operations do not fire the onresize event.

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.

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>

Mouse Rollover Effect

In its most common form, a rollover consists of an image inside a hypertext link. The image changes appearance to attract attention to the link. For example, you could add a glow effect, a drop shadow or simply change the background color. The image object arrays are preloaded to avoid delays in transmission. onMouseOver and onMouseOut events detect a rollover or rolloff. These events trigger changes in the image.src property (ie different images). Here is an example of some functions which can be added to the document head section or saved as a separate .js file:

// preload images to avoid delays
overImg=[];outImg=[];
outImg[0]=new Image();outImg[0].src="images/enter1.gif";
overImg[0]=new Image();overImg[0].src="images/enter2.gif";
outImg[1]=new Image();outImg[1].src="images/keio.gif";
overImg[1]=new Image();overImg[1].src="images/inria.gif";
function chgImg(img,type){
  switch(type){
    case "over":document.images[img].src=overImg[img].src;break;
    case "out":document.images[img].src=outImg[img].src;break;
  }}

And the HTML document code to be used for each rollover area is:

<a onMouseOver='chgImg("0","over");' onMouseOut='chgImg("0","out");'
  onfocus='chgImg("0","over");' onblur='chgImg("0","out");' href="#.">
<img src="images/enter1.gif" alt="*"/></a>

and here is what it looks like ...

*

NOTE: Images were created using a freeware paint tool by adding a hot wax effect and a drop shadow to the text.

* And here is a second rollover to show how the Javascript portion is reusable. In fact every rollover on your site can be pointed to the same external .js file if you wish!

Note: Make sure that all of the images are the same width and height. An alternative is to add width and height rules to the img element styling to ensure the images are all shown at the same size.

Timed Ad Cycler

If your website has several sponsors, then you can use an image link that cycles through each of the sponsor's ads in turn. The first step is to create an image for each of your sponsors' banner ad. All the images should have the same size. The corresponding URLs for the images and for the websites are then loaded into the arrays named adImages and adURLs defined at the start of the script. The img element for the link should be initialized to the first image in the array. The delay between ads is set by the setTimeout() method. The display is pointed at by the identifier AdBanner. The cycling is started by using the onLoad event in the body element.

adImages=["images/mit.gif","images/inria.gif", "images/keio.gif"];
adURLs=["www.lcs.mit.edu","www.inria.fr","www.keio.ac.jp"];thisAd=0;
function gotoAd(){location.href="http://"+adURLs[thisAd];}
function cycleAds(){
  if(++thisAd===adImages.length){thisAd=0;} //move to next ad
  document.images.adBanner.src=adImages[thisAd]; //show current
  setTimeout(cycleAds,3000);}  //change every 3 seconds

The above is placed in the head section and the following in the body:

<body onLoad="cycleAds()">
...
<a href="javascript:gotoAd()">
<img id="adBanner" style="height:55px;width:50px"
  src="images/mit.gif" alt="Our sponsors"/></a>

Our Sponsors: Our sponsors

The banner ad cycling concept can be easily extended to present a slideshow to viewers.

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.


JR's HomePage | Comments [jstutor4.htm:2012 07 22]