Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

I want to handle F1-F12 keys using JavaScript and jQuery.

I am not sure what pitfalls there are to avoid, and I am not currently able to test implementations in any other browsers than Internet Explorer 8, Google Chrome and Mozilla FireFox 3.

Any suggestions to a full cross-browser solution? Something like a well-tested jQuery library or maybe just vanilla jQuery/JavaScript?

like image 702
cllpse Avatar asked Jan 08 '09 14:01

cllpse


2 Answers

I agree with William that in general it is a bad idea to hijack the function keys. That said, I found the shortcut library that adds this functionality, as well as other keyboard shortcuts and combination, in a very slick way.

Single keystroke:

shortcut.add("F1", function() {     alert("F1 pressed"); }); 

Combination of keystrokes:

shortcut.add("Ctrl+Shift+A", function() {     alert("Ctrl Shift A pressed"); }); 
like image 59
matsev Avatar answered Sep 25 '22 10:09

matsev


The best source I have for this kind of question is this page: http://www.quirksmode.org/js/keys.html

What they say is that the key codes are odd on Safari, and consistent everywhere else (except that there's no keypress event on IE, but I believe keydown works).

like image 45
mcherm Avatar answered Sep 24 '22 10:09

mcherm