Event Handling in JavaScript
by K. Yue, revised: September 29, 2000
copyright 2000

Introduction

Example:

For the events Click, Change and MouseOver, the event handlers are onClick, onChange and onMouseOver respectively.

Example:

<form name="myForm">
    <input type="TEXT" name="Age" size="3"
           onChange="isNumber(this)">
    <input type="button" value="evaluate"
           onClick="evaluate(this.form)">
    ...
</form>

Note that the keyword this refers to the current object, the evalute button.
The property this.form refers to the form containing the button, that is, document.myForm.

<input type="button" name="newWinButton"
       value="open a new window"
       onClick="window.open('newdoc.html', 'myNewWindow')">

Example: eval.html

<head>
<script>
<!--- Hide script from old browsers
function compute(f) {
    if (confirm("Are you sure?"))
        f.result.value = eval(f.expr.value)
    else
        alert("Please come back again.")
}
//    end hiding from old browsers -->
</script>
</head>

<body>
<form>
Enter an expression:
<input type="text" name="expr" size="15"
       onChange="compute(this.form)">
<input type="button" value="Calculate" onClick="compute(this.form)">
<br>
Result:

<input type="text" name="result" size="15">
</form>
</body>

Example:

document.myForm.myButton.onclick=updateSomething;

Event Applies to Occurs when Event handler
Abort

images

User aborts the loading of an image (for example by clicking a link or clicking the Stop button)

onAbort
Blur

windows and all form elements

User removes input focus from window or form element

onBlur
Change

text fields, textareas, select lists

User changes value of element

onChange
Click

buttons, radio buttons, checkboxes, submit buttons, reset buttons, links

User clicks form element or link

onClick
DragDrop

windows

User drops an object onto the browser window, such as dropping a file on the browser window

onDragDrop
Error

images, windows

The loading of a document or image causes an error

onError
Focus

windows and all form elements

User gives input focus to window or form element

onFocus
KeyDown

documents, images, links, text areas

User depresses a key

onKeyDown
KeyPress

documents, images, links, text areas

User presses or holds down a key

onKeyPress
KeyUp

documents, images, links, text areas

User releases a key

onKeyUp
Load

document body

User loads the page in the Navigator

onLoad
MouseDown

documents, buttons, links

User depresses a mouse button

onMouseDown
MouseMove

nothing by default

User moves the cursor

onMouseMove
MouseOut

areas, links

User moves cursor out of a client-side image map or link

onMouseOut
MouseOver

links

User moves cursor over a link

onMouseOver
MouseUp

documents, buttons, links

User releases a mouse button

onMouseUp
Move

windows

User or script moves a window

onMove
Reset

forms

User resets a form (clicks a Reset button)

onReset
Resize

windows

User or script resizes a window

onResize
Select

text fields, textareas

User selects form element's input field

onSelect
Submit

forms

User submits a form

onSubmit
Unload

document body

User exits the page

onUnload

Example:

In a mousedown event, the event object contains

 
Property Description
data

Returns an array of strings containing the URLs of the dropped objects. Passed with the DragDrop event.

height

Represents the height of the window or frame.

layerX

Number specifying either the object width when passed with the resize event, or the cursor's horizontal position in pixels relative to the layer in which the event occurred. Note that layerX is synonymous with x.

layerY

Number specifying either the object height when passed with the resize event, or the cursor's vertical position in pixels relative to the layer in which the event occurred. Note that layerY is synonymous with y.

modifiers

String specifying the modifier keys associated with a mouse or key event. Modifier key values are: ALT_MASK, CONTROL_MASK, SHIFT_MASK, and META_MASK.

pageX

Number specifying the cursor's horizontal position in pixels, relative to the page.

pageY

Number specifying the cursor's vertical position in pixels relative to the page.

screenX

Number specifying the cursor's horizontal position in pixels, relative to the screen.

screenY

Number specifying the cursor's vertical position in pixels, relative to the screen.

target

String representing the object to which the event was originally sent. (All events)

type

String representing the event type. (All events)

which

Number specifying either the mouse button that was pressed or the ASCII value of a pressed key. For a mouse, 1 is the left button, 2 is the middle button, and 3 is the right button.

width

Represents the width of the window or frame.

x

Synonym for layerX.

y

Synonym for layerY.


Example: MouseDown.html

<script language="JavaScript1.2">
function fun1(e){
    alert ("Document got an event: " + e.type);
    alert ("x position is " + e.layerX);
    alert ("y position is " + e.layerY);
    if (e.modifiers & Event.ALT_MASK)
        alert ("Alt key was down for event.");
    return true;
}

document.onmousedown = fun1;
</script>

window.captureEvents(Event.CLICK | Event.MOUSEDOWN | Event.MOUSEUP);

function clickHander(e){
//    the event object will be passed as the actual
//    argument of e.
...
}
window.onClick = clickHandler;

Example:

function clickHandler(e) { return true; }
...
//    Let the object in the event handling hierarchy
//    to handle the event.
function clickHandler(e){
    var retval = routeEvent(e);
    return retval;
}

Example:

If you wanted all click events to go to the first link on the page, you could use:

function clickHandler(evnt) {
    window.document.links[0].handleEvent(evnt);
}

As long as the link has an onClick handler, the link handles any click event it receives.

Example: EmailCheck.html

<html>
<head>
<script language="JavaScript">
<!-- Hide from JavaScript-Impaired Browsers
/* very simple email address check. */
function emailCheck(inbox) {
    if (inbox.value.indexOf("@")<2){
        alert("I'm sorry. This email address seems wrong. Please"
              +" check the prefix and '@' sign.");
    }
}
// End Hiding -->
</script>
</head>
<body bgcolor="#9999ff">
<form>
Your email address please:
<input type="text" name="email" size="40" VALUE=""        onChange="emailCheck(this);"><br>
Other input<INPUT TYPE="txt" Name="others" SIZE=40>
<br>
<input type="submit" name="email submit" VALUE="Submit">
</form>
</body>
</html>

Example: NumberInteger.html

<html>
<head>
<script language="JavaScript">
<!-- Hide from JavaScript-Impaired Browsers
function isDigit(c) {
     return ((c >= "0") && (c <= "9"));
}

function isInteger(s){
    var i;
    for (i = 0; i < s.length; i++)
        if (!isDigit(s.charAt(i))) return false;
    return true;
}

function integerCheck(s) {
    if (!isInteger(s))
        alert("This is not an integer. Please input again.");
}

// End Hiding -->
</script>
</head>
<body bgcolor="#9999ff">
<form>
Please input an integer:
<input type="text" NAME="number" size="40" value=""        onChange="integerCheck(this.value);"><br>
Other input:<input type="txt" name="others" size="40">
<br>
<input type="submit">
</body>
</html>