Event Handling

With HTML 4.0, we were given the ability to tie scripts to certain events triggered on a web page. The most famous use of events is still probably JavaScript rollovers on links, triggered by the onmouseover and onmouseout events. Of course, CSS can handle that much easier now, but it doesn’t render events useless, as there are many we can tap into (see Table 26-5) and put to good use.

Table 26-5. Common events

Event handler

Event

onblur

An element loses focus (note: buggy).

onchange

The content of a field changes.

onclick

The mouse clicks an object.

onerror

An error occurs when loading a document or an image.

onfocus

An element gets focus.

onkeydown

A keyboard key is pressed.

onkeypress

A keyboard key is pressed or held down.

onkeyup

A keyboard key is released.

onload

A page or an image is finished loading.

onmousedown

A mouse button is pressed.

onmousemove

The mouse is moved.

onmouseout

The mouse is moved off an element.

onmouseover

The mouse is moved over an element.

onmouseup

A mouse button is released.

onsubmit

The submit button is clicked on a form.

Tapping into events is not all that difficult to do. That said, there are good ways and bad ways. The old way to tap into an event was to place it inline as an attribute of the element you wanted the event handled on:

 <a href="http://www.oreilly.com" onmouseover="window.status='Go to the O\'Reilly website'; return true;" onmouseout="window.status=''; return ...

Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.