← 5.6 Offline Web applicationsTable of contents6.2 Timers →
  1. 6 Web application APIs
    1. 6.1 Scripting
      1. 6.1.1 Introduction
      2. 6.1.2 Events

6 Web application APIs

6.1 Scripting

6.1.1 Introduction

Various mechanisms can cause author-provided executable code to run in the context of a document. These mechanisms include, but are probably not limited to:

6.1.2 Events

Many objects can have event handlers specified. These act as bubbling event listeners for the object on which they are specified.

An event handler can either have the value null or be set to a Function object.

Event handlers are exposed in one or two ways.

The first way, common to all event handlers, is as an event handler IDL attribute.

The second way is as an event handler content attribute. Event handlers on HTML elements and some of the event handlers on Window objects are exposed in this way.

Event handler content attributes, when specified, must contain valid JavaScript code matching the FunctionBody production. [ECMA262]

When an event handler content attribute is set on an element owned by a Document that is not in a browsing context, the corresponding event handler is not changed.

Event handlers always fire before event listeners attached using addEventListener().

The Function interface represents a function in the scripting language being used. It is represented in IDL as follows:

[Callback=FunctionOnly, NoInterfaceObject]
interface Function {
  any call(in any... arguments);

The call(...) method is the object's callback.

In JavaScript, any Function object implements this interface.

If the Function object is a JavaScript Function, then when it is invoked by the user agent, the user agent must set the thisArg (as defined by ECMAScript edition 5 section 10.4.3 Entering Function Code) to the event handler's object. [ECMA262]

For example, the following document fragment:

<body onload="alert(this)" onclick="alert(this)">

...leads to an alert saying "[object Window]" when the document is loaded, and an alert saying "[object HTMLBodyElement]" whenever the user clicks something in the page.

The return value of the function affects whether the event is canceled or not: if the return value is false, the event is canceled (except for mouseover events, where the return value has to be true to cancel the event). With beforeunload events, the value is instead used to determine the message to show the user.