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

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

Events in JavaScript

This chapter is from the book

The Event Object

When a W3C event listener’s event occurs and it calls its associated function, it also passes a single argument to the function—a reference to the event object. The event object contains a number of properties that describe the event that occurred.

Table 4.2 lists the names of the most commonly used properties of the event object, which of course usually differ between the W3C and Microsoft models.

Table 4.2. This table contains a list of the most commonly used event object properties.

W3C Name

Microsoft Name

Description

e

window.event

The object containing the event properties

type

type

The event that occurred (click, focus, blur, etc.)

target

srcElement

The element to which the event occurred

keyCode

keyCode

The numerical ASCII value of the pressed key

shiftKey

altKey

cntlKey

Returns 1 if pressed, 0 if not

currentTarget

fromElement

The element the mouse came from on mouseover

relatedTarget

toElement

The element the mouse went to on mouseout

By convention, the parameter name e is used in event-triggered functions to receive the event object argument. If I wanted to determine the type of event that occurred, such as a click, I would write:

function myEvent(e) {
   var evtType = e.type
   alert(evtType)
   // displays click, or whatever the event type was
}

This code would not work on a Microsoft browser, because the Microsoft model does not pass an event object reference like the W3C model; instead, it uses a central global object that contains the properties of the most recent event. I’ll start with the W3C approach and then show you how to work with the Microsoft event object.

To demonstrate the W3C model, I’ll use two event object properties as I modify the two functions in the preceding example so that those functions no longer have to get the target element before modifying it.

This takes two simple steps: I’ll add the parameter to accept the event object, and then replace the “get” of the field element with the target property of the event:

Code 4.5. hilite_field_basic4.html

function addHighlight(e) {
   var emailField=document.getElementById("email");
   var emailField=e.target;
   emailField.style.border="3px solid #6F3";
   }
function removeHighlight(e) {
   var emailField=document.getElementById("email");
   var emailField=e.target;
   emailField.style.border="";
   }

There is no visual change—see Figures 4.4 and 4.5.

You could now assign this same event listener to multiple input fields, and those fields would all display the highlight behavior. Instead of stating “highlight this field,” the code now states “highlight the field to which the event occurred.”

The Event Object’s Type Property

With access to the event object, I can now also determine the type of the event that occurred (focus, blur, click, etc.), so I can use a single function to detect both the focus and blur events.

To do this, I’ll change the event listeners to call the same function, checkHighlight. This name makes more sense for the new function, which will add and remove the highlighting.

104fig01.jpg

I’ll then change the name of the addHighlight function to checkHighlight, delete the removeHighlight function entirely, and modify the checkHighlight function to look like this:

Code 4.6. hilite_field_basic5.html

function checkHighlight(e) {
   switch (e.type) {
      case "focus":
         e.target.style.backgroundColor="#6F3";
         break;
   case "blur":
        e.target.style.backgroundColor="";
        break;
   }
}

There is no visual change—see Figures 4.4. and 4.5.

This function is pretty self-explanatory. The switch statement checks if the event type (highlighted) is focus or blur and branches the code accordingly.

The Event Object in Microsoft Browsers

So far you’ve learned that when an event listener triggers a function in W3C-compliant browsers, a reference to an object containing properties that describe the triggering event is passed to the function; this event object can be accessed through the e parameter.

In Microsoft browsers, the model is slightly different. There is one global object, window.event, that holds the last event that occurred. Because it’s global, it doesn’t have to be passed to the function like the W3C event object; it’s always available to your code. For comparison, these two lines are equivalent in their respective browsers:

105fig01.jpg

The simplest way to write cross-browser event object code is like this:

105fig02.jpg

While this works fine, branching your code for every event object property you want to use gets old fast. A better solution is to get the object, whichever kind it is, and give it a new name. Peter-Paul Koch uses the OR operator very neatly to achieve this.

var evt = e || window.event;

If e evaluates to true (a W3C event object exists), the evt variable is set to e—the W3C event object with all its properties. If not, evt is set to the Microsoft object instead. So now this works in both browsers:

var evt = e || window.event;
alert (evt.type)

The preceding example works because, unlike many event object properties, the property name for the type of event that occurred is the same—type—in both kinds of browsers. If you want to get the event target, which is target for W3C and eventSrc for Microsoft, you can build on the previous step and again use an OR statement to create a common cross-browser name (highlighted) for the event target, too:

var evt = e || window.event;
var evtTarget = evt.target || evt.srcElement;
alert(evtTarget);

Once you start working with the event object, you can manage collections of events within a single function. I’ll now add this idea into the code.

Code 4.7. hilite_field_basic6.html

106fig02.jpg

Again, there is no visual change, just much better code. See Figures 4.4 and 4.5.

Now you have a working cross-platform version of a single form field. The next step is to make the event handlers attach themselves to as many text inputs as the form might contain. Let’s add a couple more form fields to the markup so users can also enter their first and last names.

Code 4.8. hilite_field_basic7.html

<div id="sign_up">
     <h3>Sign up for our newsletter</h3>
     <form id="email_form" action="#" method="post">
        <label for="first_name">First Name</label>
        <input id="first_name" name="first_name" type="text"
           size="18" />
        <label for="last_name">Last Name</label>
        <input id="last_name" name="last_name" type="text"
           size="18" />
        <label for="email">Email</label>
        <input id="email" name="email" type="text" size="18" 
           />
        <input id="submit" type="submit" value="Go!" />
     </form>
   </div>

Figure 4.6 shows this revised markup.

Figure 4.6

Figure 4.6 The new markup has three form fields.

Because I am now working with several form elements, my hook into the DOM will be higher up at the form element’s ID, email_form. Once I have this parent element I can get at all the form’s child elements within. I’ll start by modifying the setUpFieldEvents function to tell me how many input tags are within the form.

Code 4.9. hilite_field_basic7.html

106fig08.jpg

The number of fields is shown in an alert dialog (Figure 4.7).

Figure 4.7

Figure 4.7 The new code indicates the form has four inputs.

I first get the form element and then all the elements inside it with the tag name input. My alert test shows me I have four inputs, not three as you might expect. The reason there are four is that the button, to which I don’t want to add the event listeners, is also an input tag: The only thing that makes it appear as a button is that it has a different type attribute—submit. Without step-by-step testing like this, I might have missed that and would have baked in a weird bug that changes the background color of the button every time it’s clicked.

I’ll worry about filtering out the button in a moment. I’ll first just loop through all the input fields and apply the event listeners to each of them, so that I can see that I’m able to highlight all the fields.

Code 4.10. hilite_field_basic8.html

106fig09.jpg

The first highlighted line counts the number of inputs and then puts that number in a variable; doing this allows me to write a more efficient loop. I could have skipped that line and simply written the loop like this:

for (i=0; i < theInputs.length; i++) { // etc.

The problem with this version is that JavaScript then has to determine the length of the theInputs node list (highlighted) every time the loop runs; counting items in arrays and node lists is a relatively slow process in JavaScript. It isn’t such a big deal with a few items like this, but if you are looping over a big data set or hundreds of table rows, the wasted time can add up. It’s always good practice to get the number of items once and store that in a variable that you then use as the loop count, as I have done here.

Now, when I click in each of the fields, they highlight and then return to their initial appearance when I click away. The event listeners are now successfully attached to each one, as illustrated in Figure 4.8.

Figure 4.8

Figure 4.8 Each field now highlights when it receives focus.

The problem, as I knew would happen when the earlier test returned four inputs, is that the button, which is also an input, now also gets the background color when I click it. Figure 4.9 shows that this looks very strange.

Figure 4.9

Figure 4.9 Applying highlight events to all the form’s inputs has the undesired effect of highlighting the button as well.

What makes the button different from the text inputs is that its type attribute is submit not text, so I can create a simple if statement filter based on this difference to identify and exclude it from having event listeners added.

I’ll first simply check that I can access the type attribute of each input by adding this line of code into the for loop.

Code 4.11. hilite_field_basic9.html

alert (theInputs[i].getAttribute("type"));

This pops up a sequence of four dialogs, which read text, text, text, and submit.

Now that I know I can differentiate the submit input, I’ll work up this bit of code into an if statement inside the for loop.

Code 4.12. hilite_field_basic10.html

110_prog01.jpg

Now, the text input form fields are still highlighting correctly, but the button no longer has event handlers added to it.

That completes this example. The code that you saw developed here will work reliably across today’s Web browsers and even back to IE5.5. It has dynamic capabilities to add the field highlighting effect to as many inputs as are present in the form. The actual end result of highlighting the field is rather simplistic and not what is important. What you should take away from this example are the key concepts illustrated here: cross-browser event listeners, event object handling, and the selective addition of event listeners to a number of like elements while filtering out unwanted elements. These are common tasks you will perform many times while making your applications respond to events.

I’ll now return to the stripe table example that I showed you in Chapter 3 and use events to make each table row highlight as the cursor moves over it. Along the way, I’ll illustrate the concepts of event bubbling and event delegation.

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.

Overview


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.

Surveys

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.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

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.

Security


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

Children


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

Marketing


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 customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


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: www.peachpit.com/u.aspx.

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 NevadaDesignatedRequest@pearson.com.

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.

Links


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