Events are treated as objects in JavaScript, just as document elements are. The event model gives programmers the tools to put dynamic control in the hands of users. As with other aspects of JavaScript, different browsers use different JavaScript event models. The ECMAScript language binding for DOM Level 3 events atttempts to standardize events in JavaScript.
As an example of the different event models, one of the most important
properties of an event is the reference to the object that fired the
event.
W3C and Mozilla use the target
property.
Microsoft uses the srcElement
property.
These examples from Deitel favor the Microsoft model.
Some event properties are shared.
For example, both models use the type
method for the name
of the event and mouse events in both models have altkey
,
button
, clientX
, clientY
,
ctrlKey
, screenX
, screenY
, and
shiftKey
properties.
Here are some JavaScript event types.
Event | Description |
abort | Web page loading interrupted by user |
blur | Focus removed from object |
change | Contents or setting for object changed |
click | Mouse button single click |
dblclick | Mouse button double click |
dragdrop | Object dragged and dropped |
error | Error before loading |
focus | Focus is applied ot object |
keydown | Key pressed down |
keypress | Key press |
keyup | Key is released |
load | Document loaded by browser |
mousedown | Mouse button pressed down |
mousemove | Mouse moved |
mouseout | Mouse moved away from object |
mouseover | Mouse over object |
mouseup | Mouse button released |
move | Object is moved |
reset | Reset button pressed |
resize | Window or frame resized |
select | Object is selected |
submit | Submit button pressed |
unload | Document is unloaded from browser |
Example onclick.html illustrates registration of the event handler for an object and event. It works in IE, but does not work in Mozilla. This modified example works with both browsers.
Example onload.html
illustrates the onload
event for the body element.
Example onerror.html illustrates an error handler within JavaScript that updates the browser's status line.
Example onmousemove.html
illustrates retrieving the location of the onmousemove
event with event properties offsetX
and
offsetY
.
The W3C model has clientX/clientY
and
screenX/screenY
, but not offsetX/offsetY
.
(There are other issues with this and other examples for Mozilla.)
Example onmouseoverout
illustrates two other mouse events: onmouseover
and
onmouseout
.
Example onfocusblur
illustrates the onfocus
and onblur
events
for form elements.
Example onsubmitreset
illustrates the onsubmit
and onreset
events
for forms.
Example bubbling illustrates event bubbling and cancelling bubbling of an event.