Chris Nizzardini

Salt Lake City, Utah Developer / Human / Blogger

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.

Chris Nizzardini has been developing web applications since 2006. He lives and works in beautiful Salt Lake City, Utah. If you’re interested in hiring me for contract work please visit IO Spring LLC.

Twitter Google+ 

, , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>