Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.keyCode vs. .which

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?

like image 388
ScottE Avatar asked Dec 17 '10 14:12

ScottE


People also ask

Should I use keycode or key?

If the system is Mac and the native keycode of the pressed key indicates that the key is 0-9, use a keycode for it. If the pressed key inputs an ASCII alphabetic or numeric character with no modifier key, use a keycode for it.

What is e keycode === 13?

key 13 keycode is for ENTER key.

What is e Which?

e. which is not an event, which is a property of the event object, which most people label as e in their event handlers. It contains the key code of the key which was pressed to trigger the event (eg: keydown, keyup).


2 Answers

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).

like image 196
T.J. Crowder Avatar answered Sep 24 '22 06:09

T.J. Crowder


jQuery normalises event.which depending on whether event.which, event.keyCode or event.charCode is supported by the browser:

// Add which for key events if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {    event.which = event.charCode != null ? event.charCode : event.keyCode; } 

An added benefit of .which is that jQuery does it for mouse clicks too:

// Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined ) {     event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); } 
like image 21
David Tang Avatar answered Sep 21 '22 06:09

David Tang