- Event Handling in JavaScript and jQuery
- Binding an Event Handler to an Event
- Binding Multiple Event Handlers
- Binding Event Handlers Using Shortcuts
- Calling Event Handlers Only Once
- Unbinding Event Handlers
- Using the Event Object
- Getting Mouse Coordinates
- Getting the Event Type
- Capturing Keystrokes
- Capturing Hover Events
- Getting Event Targets
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:
- 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.
- 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>
- 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>
- Save the file.
- Navigate to the file in your browser.
- Type a character; the character you typed is echoed in the page (Figure 4.8).
Figure 4.8 Reading keystrokes.