Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

Events in JavaScript

Charles Wyke-Smith shows you how to monitor and respond to events in JavaScript.
This chapter is from the book

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 Category

Event Triggered When...

Event Handler

Browser events

Page completes loading


Page is removed from browser window


JavaScript throws an error


Mouse events

User clicks over an element


User double-clicks over an element


The mouse button is pressed down over an element


The mouse button is released over an element


The mouse pointer moves onto an element


The mouse pointer leaves an element


Keyboard events

A key is pressed


A key is released


A key is pressed and released


Form events

The element receives focus from pointer or by tabbing navigation


The element loses focus


User selects type in text or text area field


User submits a form


User resets a form


Field loses focus and content has changed since receiving focus


Techniques to Handle Events

In this section, I’ll show you four techniques that you can use to trigger JavaScript functions in response to events. The first two require adding JavaScript into the markup, so I try to avoid them, preferring techniques where event handlers are programmatically added to and removed from elements as needed. In small projects, such as simple Web sites, the first two techniques work just fine, but with important caveats that I will discuss for each one.

JavaScript Pseudo Protocol

If you worked with JavaScript in years past, you may have used the the JavaScript pseudo protocol to trigger a function from a link:

<a href="javascript:someFunctionName();">Link Name</a>

When the user clicks the link, the function someFunctionName is called. No onclick is stated; this technique simply replaces the href value. The problem with this approach is that it completely replaces the URL that normally would be the href value. If the user doesn’t have JavaScript running or the associated JavaScript function fails to load for some reason, the link is completely broken. This approach also adds JavaScript into the markup, an issue I’ll discuss after I show you the second method. In short, avoid triggering events with the pseudo protocol.

Inline Event Handler

An inline event handler, as you saw briefly in Chapter 2, attaches an event handler directly to an element.

<input type="text" onblur="doValidate()" />

Here, a form text field has the JavaScript function doValidate associated with its blur event—the function will be called when the user moves the cursor out of the field by pressing Tab or clicks elsewhere. The function could then check if the user actually typed something in the field or not.

Inline event handlers have been the standard way of triggering events for years, so if you have to work on a Web site that has been around for a while, you will no doubt see inline handlers all over the markup. A benefit of inline handlers is that the this keyword is bound to the function that is called from an inline handler. To illustrate this point, here’s a link that calls a function named addClass

<a href="somePage.html onClick="addClass()">

so in the function you can simply write


without having to first “get” the element.

Additionally, you don’t have to worry about users triggering JavaScript events that act on the DOM before the DOM has loaded into the browser, because the event handler is attached to the markup. We’ll examine this DOM ready issue in “The First Event: load” section of this chapter.

However, both benefits can be realized using the two other ways of associating events with elements. Before I describe them, keep in mind that neither of the first two techniques is ideal in that they mix JavaScript with the HTML. In the previous example, the addClass function is permanently associated with this HTML element. If you change the function’s name or remove it from your code, you’ll also have to find and remove every occurrence of the handler in the markup. Also, if for some reason the addClass script doesn’t load, JavaScript will throw an error when the link is clicked. In a modern Web application—in the interests of accessibility, maintainability, and reliability—you want to keep JavaScript and CSS out of your HTML markup.

Because inline handlers are still widely used, it would be remiss of me not to show you how they work in some detail, because they will be around for years to come. In later chapters, I’ll show you examples of inline handlers and how to use them. That said, I hope they will be fading into obscurity as programmers become more aware of Web standards and the advantages of using JavaScript to register events with their associated elements. With all this in mind, let me now show you the ways you can create responses to events without adding JavaScript into the HTML markup.

Handler as Object Property

var clickableImage=document.getElementById("dog_pic");


This example shows a two-step process. First, I assign an object—an HTML element with the ID dog_pic—to a variable. In line 1 of the example, the object representing the HTML element is stored in the clickableImage variable. Second, I assign the event handler onclick as a property of the object, using a function name as the onclick property’s value. The function showLargeImage will now run when the user clicks on the element with the ID dog_pic.

While this technique has the desirable quality of keeping the JavaScript out of the markup, it has a couple of serious drawbacks.

First, only one event at a time can be assigned using this technique, because only one value can exist for a property at any given time. I can’t assign another event to the onclick property without overwriting this one, and for the same reason, another event that was previously assigned is overridden by this one.

Second, when the user clicks on this element and the function is called, that function has to be hard-coded with the name of the object so that it knows which element to work on.

function showLargeImage() {
  // do something with the pic

If you change the object that is the source of the event, you will also have to modify the function.

For this reason, the “handler as object property” technique is suitable only when you just want to assign one event to one object, such as running an initial onload function once the page is first loaded (see “The First Event: load” section later in this chapter). However, for the reasons noted, it really doesn’t provide a robust solution for use throughout an RIA, where events commonly get assigned and removed from objects as the application runs. In almost every case, the best way to manage events is to use event listeners.

Event Listeners

Introduced with the W3C DOM model, event listeners provide comprehensive event registration.

An event listener does what its name suggests: After being attached to an object, it then listens patiently for its event to occur. When it “hears” its event, it then calls its associated function in the same way as the “handlers as object properties” method but with two important distinctions.

First, an event listener passes an event object containing information about its triggering event to the function it calls. (I emphasize this point because it is so important.) Within the function, you can read this object’s properties to determine the target element, the type of event that occurred—such as click, focus, mousedown—and other useful details about the event.

This capability can reduce coding considerably, because you can write very flexible functions for key tasks, such as handling clicks, that provide variations in their response depending on the calling object and triggering event. Otherwise, you would have to write a separate, and probably very similar, function for every type of event you have to handle. You will learn how to write functions with this kind of flexibility later in the chapter.

Second, you can attach multiple event listeners to an object. As a result, you don’t have to worry when adding one listener that you are overwriting another that was added earlier, as you do when simply assigning an event as an object property.

While both the W3C and Microsoft browsers enable event handlers, they differ in the way those handlers are attached to elements and in the way they provide access to the event object. I’ll start with the W3C approach, which will be the de facto standard in the future, and then discuss how event listeners work in Microsoft browsers.

W3C Event Model

Here’s the W3C technique for adding listeners to elements. I’ll add two listeners to a form’s text field that will cause functions to run when the user clicks (or tabs) into or out of the field:


Now the function doHighlight will be called when the cursor moves into the field, and the function doValidate will be called when the cursor moves out of the field. (The third argument, false, relates to event bubbling, a concept that can wait until later in this chapter.) I can attach as many event listeners as I want to the object in this manner.

I can remove the events from the element in a similar way using the removeEventListener method.


The Microsoft Event Model

Microsoft’s event registration model is slightly different. The equivalent of this W3C style


in the Microsoft model is


and the equivalent of this W3C style


in the Microsoft model is


Note the use of on, as in onfocus, in the name of the event for the Microsoft version. Clearly, there are some syntax variations here, so let’s look at how to write code that works on both browsers.

An Addevent Helper Function

To add event listeners to elements correctly, regardless of the user’s browser type, I’ll use an existing helper function written by John Resig that can determine the correct event models to use. This function accepts the following arguments:

  • The element to which the listener should be attached
  • The type of event to listen for
  • The name of the function to call when the event occurs

It will then use these arguments to construct a correctly formatted event listener registration for the user’s browser.

The function first tests if the browser supports Microsoft’s attachEvent method (highlighted) and then branches the code accordingly.


Removing events can be achieved with a second, similar helper function.


These functions, as you can see, are somewhat complex, but fortunately you don’t have to understand them; you just have to be able to use them. If you wanted to add an event listener to the email field from the preceding example, all you would have to do is call the addEvent helper function like this:

addEvent(emailField, 'focus', doHighlight);

The three arguments are the element, the event, and the function to call when that element receives that event. The function then takes care of formatting the event registration appropriately for the browser on which it is running.

A common time at which to add listeners to elements is when the page first loads, or to be more specific, upon an event that virtually every JavaScript application must detect and handle—the load event that is triggered when the page is fully loaded and rendered in the browser.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive:

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020