Object Events in JavaScript

Creating an event handler

An event handler is added to an HTML tag as an HTML tag attribute. The SCRIPT tag is not required. A function could also be called in this case.

<\A HREF = "http://home.att.net/~Gavin.Powell" onMouseOver = "window.alert ('Moved over link http://home.att.net/~Gavin.Powell');">Click here
Click here

Changing event handlers with JavaScript

An event handler can be assigned to a function. Thus a function with an event handler contained within it can be assigned as an event handler for an HTML tag. This allows the setting of event handlers conditionally, allowing those event handlers to be turned on and off. Also the function that handles the event can be altered. Event handlers are stored as properties of the document object or another object that can receive an event. The following statements define a function called mouseAlert and then assign it as the onMouseDown event handler for the document.

function mouseAlert ()
	alert ("You clicked the mouse");
document.onMouseDown = mouseAlert;

The event object

Mouse events

Keyboard events

onKeyPress is a keyboard event.

<\BODY onKeyPress = window.alert ('The ' + String.fromCharCode (event.which) + ' key was pressed');

The onLoad event

This event is executed on the loading of a web page.

<\BODY onLoad = "alert ('Loading complete');">