Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL

Chapter 4. Events

Chapter 4. Events

In a modern web site or browser-based application, JavaScript’s primary purpose is to provide responses to the user interactions with the interface, or to be more technically precise, to handle events that are triggered by user actions.

Events are messages that the browser fires off in a constant stream as the user works; for example, every time the user moves the pointer over an HTML element, clicks the mouse, or moves the cursor into a field of a form, a corresponding event message is fired. JavaScript receives these messages, but does nothing unless you provide an event handler that provides a response to them.

Your ability to write code that can monitor and respond to the events that matter to your application is key to creating interactive interfaces.

To make your application respond to user action, you need to:

  1. Decide which events should be monitored

  2. Set up event handlers that trigger functions when events occur

  3. Write the functions that provide the appropriate responses to the events

You’ll see the details of this process throughout this chapter. For now, just get the idea that an event, such as click, is issued as the result of some specific activity—usually user activity, but sometimes browser activity such as a page load—and that you can handle that event with an event handler. The event handler is always the name of the event preceded by “on”; for example, the event click is handled by the onclick event handler. The event handler causes a function to run, and the function provides the response to the event. Table 4.1 lists the most commonly used event handlers.

Table 4.1. This table contains a list of the most commonly used event handlers.
Event CategoryEvent Triggered When...Event Handler
Browser eventsPage completes loadingonload
 Page is removed from browser windowonunload
 JavaScript throws an erroronerror
Mouse eventsUser clicks over an elementonclick
User double-clicks over an elementondblclick
The mouse button is pressed down over an elementonmousedown
The mouse button is released over an elementonmouseup
The mouse pointer moves onto an elementonmouseover
The mouse pointer leaves an elementonmouseout
Keyboard eventsA key is pressedonkeydown
 A key is releasedonkeyup
 A key is pressed and releasedonkeypress
Form eventsThe element receives focus from pointer or by tabbing navigationonfocus
The element loses focusonblur
User selects type in text or text area fieldonselect
User submits a formonsubmit
User resets a formonreset
Field loses focus and content has changed since receiving focusonchange

  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint