Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  158] [ 4]  / answers: 1 / hits: 122851  / 14 Years ago, fri, december 17, 2010, 12:00:00

I thought this would be answered somewhere on Stack Overflow, but I can’t find it.



If I’m listening for a keypress event, should I be using .keyCode or .which to determine if the Enter key was pressed?



I’ve always done something like the following:



$(#someid).keypress(function(e) {
if (e.keyCode === 13) {
e.preventDefault();
// do something
}
});


But I’m seeing examples that use .which instead of .keyCode. What’s the difference? Is one more cross-browser friendly than the other?


More From » jquery

 Answers
20

Note: The answer below was written in 2010. Here many years later, both keyCode and which are deprecated in favor of key (for the logical key) and code (for the physical placement of the key). But note that IE doesn't support code, and its support for key is based on an older version of the spec so isn't quite correct. As I write this, the current Edge based on EdgeHTML and Chakra doesn't support code either, but Microsoft is rolling out its Blink- and V8- based replacement for Edge, which presumably does/will.






Some browsers use keyCode, others use which.



If you're using jQuery, you can reliably use which as jQuery standardizes things; More here.



If you're not using jQuery, you can do this:



var key = 'which' in e ? e.which : e.keyCode;


Or alternatively:



var key = e.which || e.keyCode || 0;


...which handles the possibility that e.which might be 0 (by restoring that 0 at the end, using JavaScript's curiously-powerful || operator).


[#94566] Wednesday, December 15, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rey

Total Points: 415
Total Questions: 100
Total Answers: 100

Location: Croatia
Member since Fri, Sep 11, 2020
4 Years ago
;