Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  10] [ 4]  / answers: 1 / hits: 125399  / 14 Years ago, fri, may 21, 2010, 12:00:00

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)


More From » javascript

 Answers
47

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>);
});

[#96722] Tuesday, May 18, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrence

Total Points: 120
Total Questions: 115
Total Answers: 87

Location: England
Member since Fri, May 22, 2020
4 Years ago
terrence questions
Sat, Jun 5, 21, 00:00, 3 Years ago
Wed, Jun 17, 20, 00:00, 4 Years ago
;