Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 09-23-2012, 07:15 AM   PM User | #1
contestcen
New to the CF scene

 
Join Date: Sep 2012
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
contestcen is an unknown quantity at this point
Reading the user's keystrokes

How can I read a user's keystrokes in JavaScript? Every example I have seen requires you to create an input area, and then it associates the keystroke events with that area. I don't want anything like that. I want the user to be able to press a key at any time, no matter where the cursor happens to be, and get the desired action. For example, a user might press a question mark "?" and the webpage could display some help text, or maybe the user could type "X" and the page would cancel the previous action.
contestcen is offline   Reply With Quote
Old 09-23-2012, 09:41 AM   PM User | #2
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,103
Thanks: 197
Thanked 2,421 Times in 2,399 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Code:
<script type = "text/javascript">

document.onkeyup = function(ev) {	
var key;
ev = ev || event;
key = ev.keyCode;
alert ("Keycode = " + key);

if (key == 13) {
alert ("You pressed the ENTER key");
}

if( ev.ctrlKey || ev.shiftKey ) {
//alert ("You pressed the Control key or the Shift Key");
return false;  // disregard
}

which = String.fromCharCode(key).toUpperCase();
if (key>=48 && key<=90) {
alert ("You pressed the " + which + " key");  
}

}
</script>
You should think carefully before introducing non-standard behaviour into your web pages. As you say, the script will trigger no matter where in the page the cursor is positioned.

Quizmaster: What is a 12-sided solid figure called?
Contestant: Well, I know that ten sides is a hexagon. So I'll say an octogon.
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.

Last edited by Philip M; 09-23-2012 at 09:46 AM..
Philip M is offline   Reply With Quote
Reply

Bookmarks

Tags
cursor, input, key, keystroke, read

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 11:38 PM.


Advertisement
Log in to turn off these ads.