Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Capturing Keystrokes

You can capture keystrokes with jQuery, although it takes a little work to figure out what key was typed.

With the keyDown, keyPress, and keyUp events, the event object's keyCode property holds the struck key's code. Note that the key code holds only the raw key code, with no information about capitalization (you can check the shiftKey property for that).

We'll look at an example to get a basic idea of how to determine which key was struck when a key event occurs. To convert from the raw key code to the character that was struck, we'll use the JavaScript method String.fromCharCode( ) (which returns capital letters).

In this example, you can type keys, and the code will display the struck key in a <p> element.

To capture keystrokes:

  1. Use a text editor (such as Microsoft WordPad) to create your Web page. We'll use the example keycode.html from the code for the book here.
  2. Enter the code to add the jQuery library to the page and bind the <body> element's keyUp event to a JavaScript function (Script 4.15).

    Script 4.15. Binding the keyUp event.

    <html>
      <head>
        <title>Capturing key events</title>
        <script
         src="https://code.jquery.com/jquery-
         latest.js">
        </script>
    
        <script>
          $(function( ){
          $('#target').bind('keyup', typer);
          });
        </script>
      </head>
    
      <body id="target">
        <h1>Capturing key events</h1>
      </body>
    </html>
    
  3. Add the code to display the key that was struck in a <p> element (Script 4.16).

    Script 4.16. Displaying the key that was struck.

    <html>
      <head>
        <title>Capturing key events</title>
        <script
         src="https://code.jquery.com/jquery-
         latest.js">
        </script>
    
        <script>
          $(function( ){
          $('#target').bind('keyup', typer);
          });
    
          function typer(event)
          {
            $('#p1').text('Character: '
           + String.fromCharCode(
           event.keyCode));
          }
        </script>
      </head>
    
      <body id="target">
        <h1>Capturing key events</h1>
        <p id="p1"></p>
      </body>
    </html>
    
  4. Save the file.
  5. Navigate to the file in your browser.
  6. Type a character; the character you typed is echoed in the page (Figure 4.8).
    Figure 4.8

    Figure 4.8 Reading keystrokes.

  • + Share This
  • 🔖 Save To Your Account