Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture key press without placing an input element on the page?

Tags:

javascript

How to capture key press, e.g., Ctrl+Z, without placing an input element on the page in JavaScript? Seems that in IE, keypress and keyup events can only be bound to input elements (input boxes, textareas, etc)

like image 950
powerboy Avatar asked May 21 '10 01:05

powerboy


2 Answers

For non-printable keys such as arrow keys and shortcut keys such as Ctrl-z, Ctrl-x, Ctrl-c that may trigger some action in the browser (for instance, inside editable documents or elements), you may not get a keypress event in all browsers. For this reason you have to use keydown instead, if you're interested in suppressing the browser's default action. If not, keyup will do just as well.

Attaching a keydown event to document works in all the major browsers:

document.onkeydown = function(evt) {     evt = evt || window.event;     if (evt.ctrlKey && evt.keyCode == 90) {         alert("Ctrl-Z");     } }; 

For a complete reference, I strongly recommend Jan Wolter's article on JavaScript key handling.

like image 119
Tim Down Avatar answered Sep 22 '22 00:09

Tim Down


jQuery also has an excellent implementation that's incredibly easy to use. Here's how you could implement this functionality across browsers:

$(document).keypress(function(e){     var checkWebkitandIE=(e.which==26 ? 1 : 0);     var checkMoz=(e.which==122 && e.ctrlKey ? 1 : 0);      if (checkWebkitandIE || checkMoz) $("body").append("<p>ctrl+z detected!</p>"); }); 

Tested in IE7,Firefox 3.6.3 & Chrome 4.1.249.1064

Another way of doing this is to use the keydown event and track the event.keyCode. However, since jQuery normalizes keyCode and charCode using event.which, their spec recommends using event.which in a variety of situations:

$(document).keydown(function(e){ if (e.keyCode==90 && e.ctrlKey)     $("body").append("<p>ctrl+z detected!</p>"); }); 
like image 37
Trafalmadorian Avatar answered Sep 20 '22 00:09

Trafalmadorian