Press the capture button without placing an input element on the page?

How to capture a keystroke, for example, Ctrl + Z, without putting the input element on the page in JavaScript? It seems that in IE, keystroke and keypress events can only be bound to input elements (input fields, text fields, etc.)

+43
javascript
May 21 '10 at 1:11
source share
5 answers

jQuery also has a great implementation that is incredibly easy to use. Here you can implement this functionality in 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 and Chrome 4.1.249.1064

Another way to do this is to use the keydown event and track event.keyCode. However, since jQuery normalizes keyCode and charCode using event.which, their specification recommends using event.which in various situations:

 $(document).keydown(function(e){ if (e.keyCode==90 && e.ctrlKey) $("body").append("<p>ctrl+z detected!</p>"); }); 
+32
May 21 '10 at 1:45
source share

For non-printable keys, such as arrow keys and keyboard shortcuts, such as Ctrl-z, Ctrl-x, Ctrl-c, which can cause some actions in the browser (for example, inside editable documents or elements), you cannot receive a click event keys in all browsers. For this reason, you should use keydown instead if you are interested in suppressing the default action for the browser. If not, keyup will do the same.

keydown event to document works in all major browsers:

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

For complete reference, I highly recommend John Voltaire's article on JavaScript keyword processing .

+46
May 21 '10 at 8:38 a.m.
source share

Code and detects ctrl + z

 document.onkeyup = function(e) { if(e.ctrlKey && e.keyCode == 90) { // ctrl+z pressed } } 
+7
May 21 '10 at 1:22 a.m.
source share

Keypress detection, including keyboard shortcuts:

 window.addEventListener('keydown', function (e) { if (e.ctrlKey && e.keyCode == 90) { // Ctrl + z pressed } }); 

The advantage here is that you do not rewrite any global properties, but instead just introduce a side effect. Not good, but definitely much less infamous than the other suggestions here.

+5
Jul 01 '17 at 17:41
source share

document.onkeydown = KeyDown;

document.onkeypress = Keypress;

and etc.

Works for me in IE

-3
May 21 '10 at 1:17
source share



All Articles