Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Sep 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    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.

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,011
    Thanks
    203
    Thanked 2,538 Times in 2,516 Posts
    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.
    Last edited by Philip M; 09-23-2012 at 09:46 AM.

    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.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •