348Part IIIDocument Objects ReferenceListing 15-41(continued) Keyboard Event Handler

January 16th, 2008

348Part IIIDocument Objects ReferenceListing 15-41(continued)

Keyboard Event Handler Lab



onKeyDown onKeyPress onKeyUp
Key Codes 0 0 0
Char Codes (IE5/Mac; NN6) 0 0 0
Modifier Keys Shift Shift Shift
Ctrl Ctrl Ctrl
Alt Alt Alt

Spend some time with this lab, and try all kinds of keys and key combinations until youunderstand the way the events and key codes work. Related Item:String.fromCharCode()method. onlosecaptureCompatibility:WinIE5+, MacIE-, NN-, Moz-, Safari- elementObject.onkeydown

Web design - 347Chapter 15Generic HTML Element Objectsdocument.getElementById( upKeyCode ).innerHTML = 0; document.getElementById( pressCharCode ).innerHTML

January 15th, 2008

347Chapter 15Generic HTML Element Objectsdocument.getElementById( upKeyCode ).innerHTML = 0; document.getElementById( pressCharCode ).innerHTML = 0; document.getElementById( upCharCode ).innerHTML = 0; restoreModifiers( ); restoreModifiers( Down ); restoreModifiers( Up ); document.getElementById( downKeyCode ).innerHTML = evt.keyCode; if (evt.charCode) { document.getElementById( downCharCode ).innerHTML = evt.charCode; } showModifiers( Down , evt); } function showKeyUp(evt) { evt = (evt) ? evt : window.event; document.getElementById( upKeyCode ).innerHTML = evt.keyCode; if (evt.charCode) { document.getElementById( upCharCode ).innerHTML = evt.charCode; } showModifiers( Up , evt); return false; } function showKeyPress(evt) { evt = (evt) ? evt : window.event; document.getElementById( pressKeyCode ).innerHTML = evt.keyCode; if (evt.charCode) { document.getElementById( pressCharCode ).innerHTML = evt.charCode; } showModifiers( , evt); return false; } function showModifiers(ext, evt) { restoreModifiers(ext); if (evt.shiftKey) { document.getElementById( shift + ext).style.backgroundColor = #ff0000 ; } if (evt.ctrlKey) { document.getElementById( ctrl + ext).style.backgroundColor = #00ff00 ; } if (evt.altKey) { document.getElementById( alt + ext).style.backgroundColor = #0000ff ; } } function restoreModifiers(ext) { document.getElementById( shift + ext).style.backgroundColor = #ffffff ; document.getElementById( ctrl + ext).style.backgroundColor = #ffffff ; document.getElementById( alt + ext).style.backgroundColor = #ffffff ; } ContinuedelementObject.onkeydown

346Part IIIDocument Objects Reference} (Cedant web hosting) return true; } By

January 15th, 2008

346Part IIIDocument Objects Reference} return true; } By assigning the checkForEnter()function to each field s onkeypressevent handler, yousuddenly add some extra power to a typical HTML form. You can intercept Ctrl+keyboard combinations (letters only) in HTML pages most effectivelyin Internet Explorer, but only if the browser itself does not use the combination. In otherwords, you cannot redirect Ctrl+key combinations that the browser uses for its own control. The onkeypresskeyCodevalue for Ctrl+combinations ranges from 1 through 26 for letters Athrough Z (except for those used by the browser, in which case no keyboard event fires). ExampleListing 15-41 is a working laboratory that you can use to better understand the way keyboardevent codes and modifier keys work in IE5+ and W3C browsers. The actual code of the listingis less important than watching the page while you use it. For every key or key combinationthat you press, the page shows the keyCodevalue for the onkeydown, onkeypress, andonkeyupevents. If you hold down one or more modifier keys while performing the key press, the modifier key name is highlighted for each of the three events. Note that when run inNN6+, the keyCodevalue is not the character code (which doesn t show up in this examplefor NN6+). Also, you may need to click the NN6+ page for the documentobject to recognizethe keyboard events. The best way to watch what goes on during keyboard events is to press and hold a key to seethe key codes for the onkeydownand onkeypressevents. Then release the key to see the codefor the onkeyupevent. Notice, for instance, that if you press the A key without any modifier key, the onkeydownevent key code is 65 (A) but the onkeypresskey code in IE (and the charCodeproperty in NN6+) is 97 (a). If you then repeat the exercise but hold the Shift key down, all threeevents generate the 65 (A) key code (and the Shift modifier labels are highlighted). Releasingthe Shift key causes the onkeyupevent to show the key code for the Shift key. In another experiment, press any of the four arrow keys. No key code is passed for theonkeypressevent because those keys don t generate those events. They do, however, gener- ate onkeydownand onkeyupevents. Listing 15-41: Keyboard Event Handler Laboratory

Enter any positive integer:

Whenever a user enters a non-number, the user receives a warning and the character is notappended to the text box s text. Keyboard events also enable you to script the submission of a form when a user presses theEnter (Return on the Mac) key within a text box. The ASCII value of the Enter/Return key is13. Therefore, you can examine each key press in a text box and submit the form whenevervalue 13 arrives, as shown in the following function: function checkForEnter(evt) { evt = (evt) ? evt : event; var charCode = (evt.charCode) ? evt.charCode : (( evt.which) ? evt.which : evt.keyCode); if (charCode == 13) { document.forms[0].submit(); return false; elementObject.onkeydown

Web server iis - 344Part IIIDocument Objects Reference} Month: Day: Year: These

January 13th, 2008

344Part IIIDocument Objects Reference}

Month: Day: Year:

These three events do not fire for all keys of the typical PC keyboard on all browser versionsthat support keyboard events. The only keys that you can rely on supporting the events in allbrowsers shown in the preceding compatibility chart are the alphanumeric keys representedby ASCII values. This includes keys such as the spacebar and Enter (Return on the Mac), butit excludes all function keys, arrow keys, and other navigation keys. Modifier keys, such asShift, Ctrl (PC), Alt (PC), Command (Mac), and Option (Mac), generate some events on theirown (depending on browser and version). However, functions invoked by other key eventscan always inspect the pressed states of these modifier keys. The onkeydownevent handler works in Mozilla-based browsers only starting with Mozilla1.4 (and Netscape 7.1). Scripting keyboard events almost always entails examining which key is pressed so that someprocessing or validation can be performed on that key press. This is where the situation getsvery complex if you are writing for cross-browser implementation. In some cases, even writ- ing just for Internet Explorer gets tricky because non-alphanumeric keys generate only theonkeydownand onkeyupevents. In fact, to fully comprehend keyboard events, you need to make a distinction between key codesand character codes. Every PC keyboard key has a key code associated with it. This key code isalways the same regardless of what other keys you press at the same time. Only the alpha- numeric keys (letters, numbers, spacebar, and so on), however, generate character codes. Thecode represents the typed character produced by that key. The value might change if you pressa modifier key. For example, if you type the A key by itself, it generates a lowercase a char- acter (character code 97); if you also hold down the Shift key, that same key produces an upper- case A character (character code 65). The key code for that key (65 for Western languagekeyboards) remains the same no matter what. That brings us, then, to where these different codes are made available to scripts. In all cases, the code information is conveyed as one or two properties of the browser s eventobject. IE seventobject has only one such property keyCode. It contains key codes for onkeydownandonkeyupevents, but character codes for onkeypressevents. The NN6/Moz1 event object, onthe other hand, contains two separate properties: charCodeand keyCode. You can find moredetails and examples about these eventobject properties in Chapter 25. The bottom-line script consideration is to use either onkeydownor onkeyupevent handlerswhen you want to look for non-alphanumeric key events (for example, function keys, arrowand page navigation keys, and so on). To process characters as they appear in text boxes, usethe onkeypressevent handler. You can experiment with these events and codes in Listing15-41 as well as in examples from Chapter 25. CautionelementObject.onkeydown

343Chapter 15Generic HTML Element Objectsdocument.getElementById( legend ).style.visibility = hidden ; } (Web and email hosting)

January 12th, 2008

343Chapter 15Generic HTML Element Objectsdocument.getElementById( legend ).style.visibility = hidden ; } function init() { var msg = ; if (navigator.userAgent.indexOf( Mac ) != -1) { msg = Press help key for help. ; } else if (navigator.userAgent.indexOf( Win ) != -1) { msg = Press F1 for help. ; } document.getElementById( legend ).style.visibility = hidden ; document.getElementById( legend ).innerHTML = msg; }

onhelp Event Handler



Name:
Year of Birth:

Related Items:window.showHelp(), window.showModalDialog()methods. onkeydownonkeypressonkeyupCompatibility:WinIE4+, MacIE4+, NN4+, Moz1+, Safari1+ When someone presses and releases a keyboard key, a sequence of three events fires in quicksuccession. The onkeydownevent fires when the key makes its first contact. This is followedimmediately by the onkeypressevent. When contact is broken by the key release, the onkeyupevent fires. If you hold a character key down until it begins auto-repeating, the onkeydownandonkeypressevents fire with each repetition of the character. The sequence of events can be crucial in some keyboard event handling. Consider the sce- nario that wants the focus of a series of text fields to advance automatically after the userenters a fixed number of characters (for example, date, month, and two-digit year). By thetime the onkeyupevent fires, the character associated with the key press action is alreadyadded to the field and you can accurately determine the length of text in the field, as shownin this simple example:

onfilterchange Event Handler


The completion of the first transition ( circle-in ) triggers thesecond ( circle-out ).

image

Related Item:filterobject. onfocusCompatibility:WinIE3+, MacIE3+, NN2+, Moz1+, Safari1+ The onfocusevent fires when an element receives focus, usually following some other objectlosing focus. (The element losing focus receives the onblurevent before the current objectreceives the onfocusevent.) For example, a text input element fires the onfocusevent whena user tabs to that element while navigating through a form via the keyboard. Clicking an ele- ment also gives that element focus, as does making the browser the frontmost application onthe client desktop. The availability of the onfocusevent has expanded with succeeding generations of script- capable browsers. In earlier versions, blur and focus were largely confined to text-orientedinput elements such as the selectelement. The windowobject received the onfocuseventhandler starting with NN3 and IE4. IE4 also extended the event handler to more form ele- ments, predominantly on the Windows operating system because that OS has a user interfaceclue (the dotted rectangle) when items such as buttons and links receive focus (so that usersmay act upon them by pressing the keyboard s spacebar). For IE5+, the onfocusevent han- dler is available to virtually every HTML element. For most of those elements, however, you cannot use blur and focus unless you assign a value to the tabindexattribute of the element s tag. For example, if you assign tabindex= 1 inside a

tag, the user can bringfocus to that paragraph (highlighted with the dotted rectangle in Windows) by clicking theparagraph or pressing the Tab key until that item receives focus in sequence. WinIE5.5 adds the onactivateevent handler, which fires immediately before the onfocusevent handler. You can use one or the other, but there is little need to include both event han- dlers for the same object unless you temporarily wish to block an item from receiving focus. Toprevent an object from receiving focus in IE5.5+, include an event.returnValue=falsestate- ment in the onactivateevent handler for the same object. In other browsers, you can usuallyget away with assigning onfocus= this.blur() as an event handler for elements such aselementObject.onfocus

340Part IIIDocument Objects Referencefalse. See the discussion of (Dedicated web hosting)

January 10th, 2008

340Part IIIDocument Objects Referencefalse. See the discussion of the ondragevent handler earlier in this chapter for more detailson the sequence of drag-related events. ExampleSee Listing 15-37 of the ondragevent handler to see how to apply the ondropevent handlerin a typical drag-and-drop scenario. Related Items:event.dataTransferobject; ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstartevent handlers. onfilterchangeCompatibility:WinIE4+, MacIE-, NN-, Moz-, Safari- The onfilterchangeevent fires whenever an object s visual filter switches to a new state or atransition completes (a transition may be extended over time). Only objects that accommodatefilters and transitions in IE (primarily block elements and form controls) receive the event. A common usage of the onfilterchangeevent is to trigger the next transition within asequence of transition activities. This may include an infinite loop transition, for which theobject receiving the event toggles between two transition states. If you don t want to get intoa loop of that kind, place the different sets of content into their own positionable elementsand use the onfilterchangeevent handler in one to trigger the transition in the other. ExampleListing 15-39 demonstrates how the onfilterchangeevent handler can trigger a secondtransition effect after another one completes. The onloadevent handler triggers the firsteffect. Although the onfilterchangeevent handler works with most of the same objects inIE4 as IE5, the filter object transition properties are not reflected in a convenient form. Thesyntax shown in Listing 15-39 uses the new ActiveX filter control found in IE5.5+ (described inChapter 30). Listing 15-39: Using the onFilterChange Event Handler

ondragenter and ondragleave Event Handlers


Select any character(s) from this paragraph, and slowly drag it aroundthe page. When the dragging action enters the large header above, thestatus bar displays when the onDragEnter event handler fires. When youleave the header, the message is cleared via the onDragLeave eventhandler.

Related Items:ondrag, ondragend, ondragstart, ondropevent handlers. ondragstart(See ondrag) ondropCompatibility:WinIE5+, MacIE-, NN-, Moz-, Safari- The ondropevent fires on the drop target element as soon as the user releases the mouse but- ton at the end of a drag-and-drop operation. Microsoft recommends that you denote a drop target by applying the ondragenter, ondragover, and ondropevent handlers to the target ele- ment. In each of those event handlers, you should set the dataTransfer.dropEffectto thetransfer effect you wish to portray in the drag-and-drop operation (signified by a different cur- sor for each type). These settings should match the dataTransfer.effectAllowedpropertythat is usually set in the ondragstartevent handler. Each of the three drop-related handlersshould also override the default event behavior by setting the event.returnValueproperty toelementObject.ondrop