Oct 27 2008
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.
1 | document.onkeypress = returnKey; |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function returnKey(evt) { var evt = (evt) ? evt : ((event) ? event : null); var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); if ((evt.keyCode == 13) && (node.type == "text")) { switch(node.id) { case 'search': getProduct(); $('search').select(); break; } } } |
To do the same thing using the JQuery framework is a bit more simple. This example JavaScript code will create keyup event:
$(document).ready(function(){ $('#IDofTextInput').bind('keyup',function(e){ // your function/code to execute goes here }) }); |
Here is some example code for creating a keypress event using the MooTools Framework for JavaScript:
window.addEvent('domready',function(){ $('IDofTextInput').addEvent('keypress',function(event){ // your function/code to execute }) }) |
Drop me a comment if this helped your or if you feel I missed something, thanks for reading.
JavaScript snippet for handling EFT check scanners posting to and searching twitter with the twitter api and php

