Producing web pages
* HTML CSS DHTML XHTML A to Z of tags        Accessibility          Design

9.3 Specify logical rather than device-dependent event handlers

Event handlers invoke scripts when specific events occur, usually because of something the user does (e.g., the mouse moves, a key is pressed, the document is loaded, etc.). For a script to react to an event, event handlers must be defined, such as onChange and onClick.

Device-dependent handlers specify the actual device in the event handler name, such as onMouseOver or onKeyPress. Logical (or generic) event handlers are interested in what happened to the element (e.g., has gained or lost focus or has been selected), not what caused it to happen (e.g., keyboard or mouse). Logical event handlers include onSelect, onFocus, and onBlur.

If you must use device-dependent attributes, provide redundant input mechanisms.

Some event handlers, when invoked, produce purely decorative effects such as highlighting an image or changing the colour of an element’s text. Other event handlers produce much more substantial effects, such as carrying out a calculation, providing important information to the user, or submitting a form. For event handlers that do more than just change the presentation of an element, the W3C suggests:

  • Use application-level event attributes. These are onfocus, onblur (the opposite of onfocus), and onselect. Note: these attributes are designed to be device-independent, but are implemented as keyboard specific events in current browsers
  • If you must use device-dependent attributes, provide redundant input mechanisms (i.e., specify two handlers for the same element):

    Use onmousedown with onkeydown
    Use onmouseup" with onkeyup
    Use onclick with onkeypress

    Note that there is no keyboard equivalent to double-clicking (ondblclick) in HTML 4.01
  • Do not write event handlers that rely on mouse coordinates since this prevents device-independent input
  • To make pop-up windows accessible to keyboard users, add the event triggers onfocus and onblur. For example:

    <a href="foo.html" onMouseOver="blah()" onFocus="blah()">