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

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

  • Print
  • + Share This
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.

  • + Share This
  • 🔖 Save To Your Account