Using JavaScript s Core HTML Events


Using JavaScript's Core HTML Events

Handling events in JavaScript has become complex in recent years because you can now do things three ways: the Netscape Navigator way, the Internet Explorer way, and the W3C way. We'll take a look at these various techniques and event handling in depth in Chapter 15, "Working with the Mouse, Keyboard, and Images," but I'll introduce the topic here. Despite the complexities, we'll be able to cover at least 95 percent of the typical JavaScript event handling here in this chapter.

Connecting an Event Handler Using Event Attributes

We've already seen how to handle events in a general wayyou can just use an HTML event attribute such as ONCLICK to connect an event to a JavaScript function, called an event handler. Here's an example from Chapter 1, "Essential JavaScript." In this case, I'm connecting a button's ONCLICK HTML attribute to a JavaScript function named alerter :

(Listing 01-04.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Executing Scripts in Response to User Action          </TITLE>  <SCRIPT LANGUAGE="JavaScript">   <!--   function alerter()   {   window.alert("You clicked the button!")   }   // -->   </SCRIPT>  </HEAD>      <BODY>          <H1>Executing Scripts in Response to User Action</H1>          <FORM>  <INPUT TYPE="BUTTON" ONCLICK="alerter()" VALUE="Click Me!">  </FORM>      </BODY>  </HTML> 

You can see the results in Figure 6.1, where I've clicked the button and the JavaScript code displays an alert box.

Figure 6.1. Using an event in the Netscape Navigator.

graphics/06fig01.gif

Connecting an Event Handler Using Object Properties

In the preceding example, I used the HTML event attribute ONCLICK to connect an event to an event handler. (Because this is an HTML attribute, it can be any mix of capital and small letters ; in this book, however, I'm capitalizing HTML to distinguish it from JavaScript, so here it's ONCLICK .) In recent browsers (NS3+ and IE4+), you also can connect an event handler in JavaScript code, using JavaScript's events such as onclick (all small letters), which enables you to change event handlers as you want. Here's an example using the onclick event in JavaScript, where I'm connecting that event to the button and the alerter function:

 <HTML>      <HEAD>          <TITLE>              Executing Scripts in Response to User Action          </TITLE>      </HEAD>      <BODY>          <H1>Executing Scripts in Response to User Action</H1>          <FORM ID="form1" NAME="form1">              <INPUT ID="button1" NAME="button1" TYPE="BUTTON" VALUE="Click Me!">          </FORM>          <SCRIPT LANGUAGE="JavaScript">              <!--  document.form1.button1.onclick = alerter  function alerter()              {                  window.alert("You clicked the button!")              }              // -->          </SCRIPT>      </BODY>  </HTML> 

Connecting an Event Handler Using <SCRIPT FOR>

In the Internet Explorer 4+, you also can use the <SCRIPT> element's FOR attribute to connect a script to a particular event. We saw this as far back as Chapter 1; for example, here's how I connect a script to the onclick event of the HTML button button1 :

(Listing 01-06.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Using the SCRIPT FOR Element          </TITLE>  <SCRIPT FOR="button1" EVENT="onclick" LANGUAGE="JavaScript">   <!--   alert("You clicked the button!")   // -->   </SCRIPT>  </HEAD>      <BODY>          <H1>Using the SCRIPT FOR Element</H1>          <FORM NAME="FORM1">  <INPUT TYPE="BUTTON" NAME="button1" VALUE="Click Me!">  </FORM>      </BODY>  </HTML> 

Connecting an Event Handler Using the attachEvent Method

There's still another way to connect an event handler to an eventyou can use the Internet Explorer attachEvent method (available in IE5+). You use this method on the HTML element you want to attach an event handler to, passing the name of the event to use (in quotes) and the event handler function (without quotes), like this:

 <HTML>      <HEAD>          <TITLE>Using the attachEvent Method</TITLE>      </HEAD>      <BODY>          <H1>Using the attachEvent Method</H1>          <FORM NAME="form1">               <INPUT TYPE="BUTTON" NAME="button1" VALUE="Click Me!">          </FORM>          <SCRIPT LANGUAGE="JavaScript">              <!--  document.form1.button1.attachEvent("onclick", alerter)  function alerter()              {                  alert("You clicked the button!")              }              // -->          </SCRIPT>      </BODY>  </HTML> 

As you can see, you can connect events to event handlers in a number of ways. In fact, that's just the beginning. Here, we've used only the simple onclick event. However, events often have more data connected with themfor example, when an onmousedown event occurs, you know the user pressed the mouse buttonbut where did the mouse event actually occur? You can find that out by using an event object.

Using event Objects

Both the Netscape Navigator and the Internet Explorer have an event object, and you can retrieve event data from this object. As we'll see in Chapter 15, however, the properties of this object vary not only by browser, but also by version. You can see a summary of some common event object properties in Table 6.2 by browser and version.

Table 6.2. Core event Object Properties

NS4

NS6

IE4+

Means

-

clientX

clientX

X location in a window

-

clientY

clientY

Y location in a window

layerX

layerX

x

X location in a positioned item

layerY

layerY

y

Y location in a positioned item

modifiers

shiftKey

shiftKey

Keyboard modifier keys

 

altKey

altKey

 
 

ctrlKey

ctrlKey

 

-

-

offsetX

X location in a container

-

-

offsetY

Y location in a container

pageX

pageX

-

X location in the page

pageY

pageY

-

Y location in the page

screenX

screenX

screenX

X location in the screen

screenY

screenY

screenY

Y location in the screen

target

target

srcElement

Element the event was targeted to

type

type

type

Type of event that occurred

-

-

wheelDelta

The distance the wheel button rolled

which

keyCode

keyCode

Keyboard key that caused the event

which

button

button

Mouse button that caused the event

Tip

Here's another good property to know of the Internet Explorer's event object: returnValue . If you set window.event.returnValue to false in an event handler, the browser does not perform the default operation it usually performs for that event. See "The oncopy Event" in this chapter for an example, where we're overriding an attempt to copy text from a web page.


Cross-Browser Event Handling

There is another difference besides the differences you see in Table 6.2in the Netscape Navigator, the event object is passed to your event handler; in the Internet Explorer before version 6.0, however, the event object is part of the window object, and you referenced it as window.event (in other words, as a global object, instead of being passed to event handlers). To account for this difference, you used to use code like this, where I'm placing the event object in a variable named e if we're working in the Netscape Navigator, we'll use the event object passed to the event handler; otherwise I'll assign window.event to e , like this:

 function handler(e)  {      //For browsers before Internet Explorer 6.0      if (!e){          e = window.event      }      //event-handling code  } 

Here's an example; in this case, I'll use the clientX and clientY properties common to the event object in both the Netscape Navigator and the Internet Explorer to discover where the mouse button was pressed. The origin for clientX and clientY is at upper left of the client area of the browser. (The client area is the display area, which doesn't include toolbars , status bars, menus , and so on.) Here's the code:

(Listing 06-01.html on the web site)
 <HTML>      <HEAD>          <TITLE>Handling Events</TITLE>      </HEAD>  <BODY ONMOUSEDOWN="display(event)">  <H1>Handling Events: Click this Page!</H1>          <FORM NAME="form1">              <INPUT TYPE="TEXT" NAME="text1"></INPUT>          </FORM>          <SCRIPT LANGUAGE="JavaScript">              <!--             function display(e)              {                  //For browsers before Internet Explorer 6.0  if (!e){   e = window.event   }   document.form1.text1.value = "You clicked (" +   e.clientX + ", " + e.clientY + ")"  }              // -->          </SCRIPT>      </BODY>  </HTML> 

Note how I've specified that the Netscape Navigator should pass an event object to the event handler here, by passing the keyword "event" : <BODY ONMOUSEDOWN="display(event)"> . This ensures that the Netscape Navigator will pass an event object to the event handler. Earlier versions of the Internet Explorer, on the other hand, will pass null here. You can see the results of this code in Figure 6.2.

Figure 6.2. Using a mouse event in the Netscape Navigator.

graphics/06fig02.gif

Tip

The Netscape Navigator attaches special attention to the "event" argument. You can use multiple arguments like this: <BODY ONMOUSEDOWN="display(this, event)"> , and the Netscape Navigator will pass the event object in the position given by the "event" argument.


The situation has changed in the Internet Explorer 6.0, however, making this kind of object detection less reliable. Perhaps because Microsoft realized that the trend is moving toward passing event objects to event handlers instead of using global event objects in the W3C DOM level 2 (which Microsoft has yet to implement), or to give programmers tackling both the Internet Explorer and Netscape Navigator a break, event handlers in Internet Explorer 6.0 now are passed to an event object (identical to window.event , which still exists and is still accessible) if you specify the "event" argument when connecting an event handler to an event, like this: <BODY ONMOUSEDOWN="display(event)"> .

This makes things a little awkward for scripts that are used to checking for a passed event object in event handlers to distinguish between the two browsers. In some cases, those scripts will have to be updated to check the name of the browser directly (using the navigator.appName property), and I'll often use that technique in this chapter.

That introduces us to event handling in the Netscape Navigator and the Internet Explorer; we'll see more on event handling, and in more depth, in Chapter 15. Besides this type of event handling, there's also another type: the W3C DOM type.

Handling Events in the W3C DOM

The W3C technique of event handling, following the lead of Java, is that you must register for the events you want to catch using a listener , which is just an event handler.

There are several listener types, one for each type of event, as you see in Table 6.3. These listeners are implemented only in the Netscape Navigator 6.0 (and not all of them at that)event handling was introduced only in the W3C DOM level 2, and the Internet Explorer supports only the W3C DOM level 1 fully. Note that there are far fewer W3C events than standard Internet Explorer and Netscape Navigator events (which you see in Table 6.1.)and also note that there is no on prefixing these names : for example, here, you use the click event, not the onclick event.

Table 6.3. W3C DOM Event Listener Types

Listeners

   

abort

blur

change

click

DOMActivate

DOMAttrModified

DOMCharacterDataModified

DOMFocusIn

DOMFocusOut

DOMNodeInserted

DOMNodeInsertedIntoDocument

DOMNodeRemoved

DOMNodeRemovedFromDocument

DOMSubtreeModified

error

focus

load

mousedown

mousemove

mouseout

mouseover

mouseup

reset

resize

scroll

select

submit

unload

   

The event object passed to a listener function in the Netscape Navigator is much like a standard NS6 event object. You can see some of the properties of W3C event objects in the Netscape Navigator in Table 6.4, which you can match up to those in Table 6.2, with the addition of the currentTarget property, which holds the current target element of an event that you've routed in ways we'll see in Chapter 15the originalTarget property, which is holds original target element of the event, the metaKey property to handle meta key events, and the timeStamp property, which holds information about when the event occurred.

Table 6.4. Some W3C DOM Event Object Properties

Properties

   

currentTarget

type

target

originalTarget

timeStamp

altKey

ctrlKey

shiftKey

metaKey

charCode

keyCode

screenX

screenY

clientX

clientY

button

layerX

layerY

pageX

pageY

which

Tip

The W3C DOM event object has a method that corresponds to the Internet Explorer's returnValue property: cancelDefault . If you call an event object's cancelDefault method, the browser does not perform the default operation it usually performs for that event. For an example using the Internet Explorer's returnValue property, see "The oncopy Event" in this chapter for an example, where we're overriding an attempt to copy text from a web page.


Here's an example. In this case, I'll add an event listener to the click event of a <SPAN> element and display the ID of the <SPAN> element when the user clicks that element. To do that, I'll use the addEventListener method, passing that method the name of the event to listen for, the event handler function, and a value of true to indicate that I want to capture this event and not route it on to another event handler (this example, which uses the addEventListener method, is targeted at Netscape Navigator 6.0):

(Listing 06-02.html on the web site)
 <HTML>      <HEAD>          <TITLE>Handling W3C Events</TITLE>      </HEAD>      <BODY>          <H1>Handling W3C Events</H1>          <P><SPAN ID="span1">Click Me.</SPAN></P>          <FORM NAME="form1">              <INPUT TYPE="TEXT" ID="text1"></INPUT>          </FORM>          <SCRIPT LANGUAGE="JavaScript">              <!--  document.getElementById("span1").addEventListener("click", display, true)   function display(e)   {   document.form1.text1.value = "You clicked: " +   e.currentTarget.id   }  // -->          </SCRIPT>      </BODY>  </HTML> 

You can see the results in Figure 6.3, where we're catching the <SPAN> element's W3C click event.

Figure 6.3. Using a W3C event in the Netscape Navigator.

graphics/06fig03.gif



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

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