Capturing function keys in web browsers

I have a web application that allows the user to press the F2 key to bring up a modal box search window (the modal box script is provided by ModalBox). Today, one of the users came to me and said that every time they press the ‘Q’ key in the search box, the modal box refreshes.

It turned out that pressing the ‘Q’ key did in fact refresh the modal box — but only in Firefox, not in Internet Explorer. Knowing that Mozilla and IE have slightly different JavaScript event capture techniques, I looked at the code I was using to capture the F2 keypress.

Event.observe(window, 'load', function() {
	Event.observe(
		document, 'keypress', function(event)
		{
			if (event.keyCode) 
				keycode=event.keyCode;
			else
				keycode=event.which;
			if (keycode==113)
				Modalbox.show('Search', '/search/quicksearch.rails', {width:360, height:90});
		}
	);
});

A little research and I found the problem: keyCode 113 is the ASCII code for the lower-case ‘q’. I needed to find a way to capture the event when the function key 113 was pressed, not the ‘q’ key 113.

The solution was to use the event.charCode exposed in Firefox. This is undefined in IE, but in Firefox it equals zero when a function key is pressed. A little revision to the JavaScript code resulted in the following (note the difference in the line that contains (keycode==113).

Event.observe(window, 'load', function() {
	Event.observe(
		document, 'keypress', function(event)
		{
			if (event.keyCode) 
				keycode=event.keyCode;
			else
				keycode=event.which;
			if (keycode==113 && (event.charCode ? event.charCode : 0) == 0)
				Modalbox.show('Search', '/search/quicksearch.rails', {width:360, height:90});
		}
	);
});

Problem solved.

One thought on “Capturing function keys in web browsers”

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=""> <s> <strike> <strong>