Reputation: 6417
I am writing event handlers in jQuery. I want to use a specific set of keys (eg arrow keys) for a particular action. Is there a shorthand notation for this?
I have this.
if(event.keycode == 37 || event.keyCode == 38 || event.keyCode == 39)
I'm wondering if there are ranges in JavaScript, like (37..40)?
Thanks in advance!
Upvotes: 1
Views: 166
Reputation: 45589
You can achieve the range effect by using the comparison operators, like so:
// keep a local reference to avoid consequent requests
var keyCode = event.keyCode;
// check if key code is in range
if(keyCode >= 37 && keyCode <= 40){
// in range, do something
} else{
// out of range, do something else
}
Upvotes: 1
Reputation: 4297
This:
var code = event.keycode;
if (code >= 37 && code < 40) { /* ... */ }
Or (not sure about IE):
var code = event.keycode;
if ([37, 38, 39].indexOf(code) != 1) { /* ... */ }
Upvotes: 1
Reputation: 5685
if(event.keycode >= 37 && event.keyCode <= 39)
Not much better in my opinion, and if its only a few key's you're after I would just include them all in the if for better code clarity.
Upvotes: 2