Chris Nizzardini, Salt Lake City Utah, Web Developer Specializing in LAMP+Ajax Since 2006

My Blog

Here is my awesome blog.

JavaScript key listener

Placing a JavaScript key listener in your web application is great way to make your app react like a desktop application. 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;
			}
		}
	}

Leave a Reply