An Example Using the Event Object


The JavaScript event object is used to access details about an event that has just occurred. This information is stored in the properties of the object (it has no methods or events).

In this section, to learn how to work with the event object, we’ll use the event object to learn what key the user pressed in a text box. The code in this example is processed when the onKeyDown event of the text box is fired. The program is also able to distinguish a specific letter—a lowercase or uppercase t —and take specific action when that letter is entered.

Of course, the “actions” this program takes don’t amount to much: The program displays an alert box showing the letter pressed and, in case of the letter t, a special, different alert box. But in the “real world,” you could take significant action depending on the letter entered by the user, and that’s one of the points of this exercise.

Let’s get started constructing the example that displays an alert box intercepting keystrokes, displaying the key pressed, and not allowing the letter t to be entered. To do this, we’ll use the keyCode property of the event object, which stores a number representing the key pressed when an onKeyDown event is fired. You should know that the number 84 represents the Unicode number, or character encoding, for the letter t.

start sidebar
Internet Explorer, Mozilla, and Netscape

This example involves another wrinkle we haven’t dealt with so far. The object and event model of Internet Explorer is slightly different from the model for other browsers. For example, Mozilla and Netscape share a common object and event model, which you’d expect if you knew that the Mozilla and Netscape ancestry is the same. However, the Mozilla and Netscape models do differ from that of Internet Explorer.

The examples in this chapter run on the three main browsers (Internet Explorer, Mozilla, and Netscape). (For all I know, they also work on other, more obscure browsers. I just haven’t tested to find out for sure.) I don’t want to get too bogged down in this stuff because it’s really not that directly related to the primary topic of this book, learning to program. But, as I’ll show you, there are two steps you need to take to make the examples in this chapter work on both object and event models:

  • Your program needs to determine which browser is running the code.

  • Your program needs to contain separate code for the two different models.

end sidebar

Tip

You can find out more about Unicode, which is a way to universally refer to letters and other characters, on the Unicode home page, http://www.unicode.org.

Creating this application involves a number of steps. We’ll need to:

  • Understand how to use the event object in an event handler

  • Access the keyCode property of the event object

  • Use the String object’s fromCharCode method to display the letter represented

  • Determine if the browser running the code is Internet Explorer or Netscape/Mozilla (see the previous sidebar for more information)

  • Intercept the letter t and delete it, using differing code depending on the object model

The event object, and its properties, can be used directly in the code assigned to an event in an HTML element. Usually, however, you’ll want to do the actual programming work in a function that’s called from a statement assigned to the event. In our case, we’ll call the function that does the work checkKey. To make the properties of the event object, which is to say the properties of the most recently fired event, available to the checkKey function, we must pass the event object as an argument to the function.

To Use the Event Object in an Event Handler:

  1. Pass the keyword event, which means the JavaScript event object, as an argument to the call to the function that will be processing the event. For example:

     <INPUT type=text name="theText" onKeyDown="checkKey(event);"> 

  2. Use the properties of the event object as you would the properties of any other event object.

The keyCode Property

The Unicode representation of a character key that has been pressed using the keyboard is contained in the keyCode property of the event object. You can use this property to respond to individual keystrokes. For example, suppose you have something against the letter t and refuse to allow it in a text box.

I just picked t at random. Really, I don’t have anything against this letter! But I did want to demonstrate how easy it is to pick out particular letters.

To Display the Key Pressed:

  1. Create a simple form that includes a text box:

     <FORM name="theForm"> <INPUT type=text name="theText"> </FORM> 

  2. Add an onKeyDown event handler to the text input:

     <INPUT type=text name="theText" onKeyDown=" "> 

  3. Add a call to a function named checkKey to the event handler:

     <INPUT type=text name="theText" onKeyDown="checkKey();"> 

  4. Pass the event object to the checkKey function by using the event keyword as an argument:

     <INPUT type=text name="theText" onKeyDown="checkKey(event);"> 

  5. Create a function named checkKey with a parameter e that represents the event object:

     function checkKey(e){  } 

    By the way, I could have used any legal identifier for the parameter e. Naming it e helps remind me that it contains event information.

  6. Check to see if the keyCode property contains the number 84 (which means that it’s a t):

     function checkKey(e){     if (e.keyCode == 84){     }     else {     }  } 

  7. If the key pressed isn’t a t, display it (see Figure 8-2):

     function checkKey(e){     if (e.keyCode == 84){     }     else {        alert ("You entered the character " +           String.fromCharCode(e.keyCode) + ".");     }  } 

    click to expand
    Figure 8-2: The letter entered by the user in the text box is displayed in an alert box.

    This code uses the String.fromCharCode method to convert the Unicode number that represents the key to its alphabetic equivalent. Note that fromCharCode is a shared (or static) member of the String class, so you don’t (and can’t) instantiate a String object to use it.

  8. If it’s a t, display an alert box (see Figure 8-3):

     function checkKey(e){     if (e.keyCode == 84){        alert("You have dotted those eyes, iconid=parrow           but you can't put any Tees in the box!");     }     else {        alert ("You entered the character " +           String.fromCharCode(e.keyCode) + ".");     }  } 

    click to expand
    Figure 8-3: The letter t is singled out for unfair treatment.

The next thing we want to do is to delete the letter t from the text box. As it turns out, this is easier in Internet Explorer than in the other browsers.

We can check to see which browser is running by inspecting the appName property of the Netscape object.

To Check to See Which Browser Is Running the Code:

  1. Check to see if the appName property of the Netscape object is Microsoft Internet Explorer:

     ...  if (Netscape.appName == "Microsoft Internet Explorer")  ...  else {      // deal with Netscape or Mozilla  } 

Note

This is really a pretty crude test. The properties of the Navigator object will give you much more detailed information, should you ever need it.

In Internet Explorer, you can remove the letter from the text box simply by setting the returnValue property of the event object to false.

To Remove the t from the Text Box in Explorer:

  1. In Microsoft Internet Explorer, cancel the results of the user’s key down action by setting the event returnValue property to false:

     e.returnValue = false; 

This makes sure that in Internet Explorer the t never appears in the text box.

Because the event object in Mozilla/Netscape doesn’t have a returnValue property, another strategy must be used to remove the letter from the text box. You have to go ahead and reach through the object model to find the text box on the form. When you’ve “got” the text box, you can take the string representing its value and use string manipulation techniques, namely the String object’s substr method, to remove the last (most recently entered) letter from the value string. This is more cumbersome than the process with Internet Explorer but not difficult.

You’ll find more information about manipulating string values in Chapter 9, “ Manipulating Strings.”

Note

The technique shown for Mozilla/Netscape works in Internet Explorer as well. But I wanted to show you how to use the handydandy returnValue property of the event object, only available in Explorer.

To Remove the Letter in Mozilla/Netscape:

  1. First, check to see which browser is running:

     if (Netscape.appName == "Microsoft Internet Explorer")     e.returnValue = false;  else {     // deal with Mozilla/Netscape  } 

  2. Next, add code to delete the letter t if it has appeared in the Mozilla/Netscape text box:

     if (Netscape.appName == "Microsoft Internet Explorer")     e.returnValue = false;  else {     str = document.theForm.theText.value;     if (str.length == 1)        newstr=" ";     else {        newstr = str.substring(0, str.length -1);     }     document.theForm.theText.value = newstr;  } 

You may notice that this little program works a little differently under Netscape than Internet Explorer. With Netscape (or Mozilla), the t does appear in the text box (see Figure 8-3) before being deleted by the checkKey function. In Internet Explorer, setting the event object returnValue to false canceled the impending action, and the t never appeared in the text box. So, the Mozilla/Netscape variant can be thought of as going back in time to erase something that happened while the Explorer version makes sure that it never happened in the first place.

Listing 8-1 shows the complete code for the program.

Listing 8.1: Intercepting an onKeyDown event, Displaying the Key Pressed, and Taking Action If It’s a Specific Key

start example
 <HTML> <HEAD> <TITLE>Keystroke detector</TITLE> </HEAD> <BODY> <SCRIPT>  function checkKey(e){     if (e.keyCode == 84){        alert("You have dotted those eyes, but you can't put any Tees in the  box!");        if (navigator.appName == "Microsoft Internet Explorer")           e.returnValue = false; //works with Explorer        else {           //deal with Netscape or Mozilla           str = document.theForm.theText.value;           if (str.length == 1)              newstr=" ";           else {              newstr = str.substring(0, str.length -1);           }           document.theForm.theText.value = newstr;        }     }     else {        alert ("You entered the character " + String.fromCharCode(e.keyCode)  + ".");     }  }  </SCRIPT> <FORM name="theForm"> <INPUT type=text name="theText" onKeyDown="checkKey(event);"> </FORM> </BODY> </HTML> 
end example




Learn How to Program Using Any Web Browser
Learn How to Program Using Any Web Browser
ISBN: 1590591135
EAN: 2147483647
Year: 2006
Pages: 115
Authors: Harold Davis

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net