How do I go about binding a function to left and right arrow keys in Javascript and/or jQuery? I looked at the js-hotkey plugin for jQuery (wraps the built-in bind function to add an argument to recognize specific keys), but it doesn't seem to support arrow keys.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
You can use the keyCode of the arrow keys (37, 38, 39 and 40 for left, up, right and down):
Check the above example here.
This is a bit late, but HotKeys has a very major bug which causes events to get executed multiple times if you attach more than one hotkey to an element. Just use plain jQuery.
Instead of using
return false;
as in the examples above, you can usee.preventDefault();
which does the same but is easier to understand and read.Put your custom code for the arrow keys between the corresponding
case
andbreak
lines.e.which
is normalized by jQuery, so it works in all browsers. For a pure javascript approach, replace the first two lines with:(edit 2017)
If you feel fancy, you can use
e.key
instead ofe.which
ore.keyCode
now.e.key
is becoming a recommended standard, allowing you to check against strings:'ArrowLeft'
,'ArrowUp'
,'ArrowRight'
,'ArrowDown'
. New browsers support it natively, check here.I've simply combined the best bits from the other answers:
Character codes: