Home arrow JavaScript arrow Page 5 - Handling events with the DOM - Part III
SEARCH DEVARTICLES

TOOLS YOU CAN USE

advertisement
Handling events with the DOM - Part III - Focusing on keys: determining which key has been pressed
(Page 5 of 7 )

 

To determine which key the user has pressed, usually we use the "keyCode" property. However, Mozilla and Netscape expose the "which" property to find out the key pressed. First, we should get the ASCII code for the key, and then turn it into the corresponding character. Taking advantage of the "String.fromCharCode()" method, this is quite easy to do. The function to obtain the key pressed is as follows:

 

function detectKey(e){

    var code;

    if(!e) var e=window.event;

    if(e.keyCode){code=e.keyCode;}

    else if(e.which){code=e.which;}

    alert(String.fromCharCode(code));

}

 

And we might call it with the statement:

 

document.onkeypress=detectKey;

 

Indeed, key detection is somewhat annoying sometimes, since “keypress”, "keyup" and "keydown" event handlers are triggered as long as the user keeps the key pressed. In Netscape, the ASCII value of the key is given by the "charCode" property on "keypress" events, and it’s present in the "keyCode" property for "keydown" and "keyup" events, while IE stores the Unicode value of the key in the event "keyCode" property for all three key events.

 

Both the " keydown" and " keyup" events will fire when any modifier key is pressed, such as ALT, CTRL and SHIFT. The "keypress" event can be used instead to capture combinations such as SHIFT-A. For keeping things simple, it’s recommended to use only one event handler at once.

 

It’s time to move forward and learn how to detect the mouse coordinates according to the event generated.

 


blog comments powered by Disqus
JAVASCRIPT ARTICLES

- More Top jQuery Tutorials for Beginners
- More Top jQuery Plugins for Menus
- Top jQuery Tutorials for Beginners
- New UI Framework and SDK for JavaScript Rele...
- JavaScript OpenPGP Tool, Node.js 0.6.3 Avail...
- Yahoo Releases Cocktails Language and Develo...
- Customizing jQuery Slideshows: Dynamic Contr...
- Customizing jQuery Slideshows: the animate()...
- Customizing jQuery Slideshows: slideUp() and...
- Customizing jQuery Slideshows: hide() and sh...
- Web Workers: Performing Calculations in Para...
- More Top JavaScript Frameworks and Libraries
- More Dynamic jQuery Styling Techniques
- The Top JavaScript Libraries
- The Top JavaScript Frameworks

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 5 - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials