How to Create a JavaScript Key Listener

Need help with JavaScript key listeners? Using a key listener in JavaScript is great way to make your web application react like a desktop application. If you’re not using a javascript framework such as MooTools or JQuery (I’ll go over these after covering generic javascript) then the first thing you need to do is place this code in your body onload event. This will call the returnKey function every time the browser detects a key press.

We will listen specifically for key code 13, the return key, where a text node has focus. Next we create a switch statement that looks at the text nodes id. We will put in a case to look for the text node id of search. This will call a getProduct function and also highlight the search field.

To do the same thing using the JQuery framework is a bit more simple. This example JavaScript code will create keyup event:

Here is some example code for creating a keypress event using the MooTools Framework for JavaScript:

Drop me a comment if this helped your or if you feel I missed something, thanks for reading.