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.
-
Possible duplicate of How to detect escape key press with pure JS or jQuery? – Alex83690 May 26 '18 at 17:23
$(document).keydown(function(e) {
switch(e.which) {
case 37: // left
break;
case 38: // up
break;
case 39: // right
break;
case 40: // down
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
Put your custom code for the arrow keys between the corresponding case
and break
lines.
e.which
is normalized by jQuery, so it works in all browsers. For a pure javascript approach, replace the first two lines with:
document.onkeydown = function(e) {
e = e || window.event;
switch(e.which || e.keyCode) {
(edit 2017)
If you feel fancy, you can use e.key
instead of e.which
or e.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.
-
28By far best answer. Uses
e.which
like jQuery recommends for cross-browser, usese.preventDefault()
instead ofreturn false
(return false
on a jQuery event handler triggers bothe.preventDefault()
ande.stopPropagation()
, the second of which is going to cause any later added events to fail since the event won't propagate to them), and at the end of the switch, will return without callinge.preventDefault()
if it's any other key than the ones being looked for to not hinder other key usage, and instead of$.ui.keyCode.DOWN
it compares to the numbers (MUCH faster). – Jimbo Jonny Nov 24 '12 at 2:41 -
2Nathan: it seems that not all keycodes are consistent among browsers, but the arrow keys are some of those that are. See here: stackoverflow.com/questions/5603195/… – Sygmoral Sep 18 '13 at 0:20
-
1@MichaelScheper - 1) variables != constants, regardless of whether or not they are intended to be changed...the engine still has to treat them like vars until ES6 constants are ubiquituous enough that jQuery can use constants 2) numbers aren't really magic numbers when there is comment right beside them telling exactly what they are, and 3) ...continued – Jimbo Jonny Jan 13 '16 at 5:22
-
2... 3) when accessing
$.ui.keyCode.DOWN
you look for$
in your lexical scope, not finding it, going up a level...looking for$
, repeat until in global scope, find it on the globalwindow
, access$
on window, accessui
onwindow.$
, accesskeyCode
onwindow.$.ui
, accessDOWN
onwindow.$.ui.keyCode
to get to the primitive value you want to compare, then do your actual comparing. Whether or not that speed matters to you is a personal decision, I just have a tendency to avoid 4 levels of accessing when there's a situation where I can just as easily write/comment the primitive. – Jimbo Jonny Jan 13 '16 at 5:30 -
1@NathanArthur Here I found two good online tools to test the keyboard keycodes: keycode.info asquare.net/javascript/tests/KeyCode.html unixpapa.com/js/key.html – Riccardo Volpe Aug 2 '17 at 21:53
$(document).keydown(function(e){
if (e.which == 37) {
alert("left pressed");
return false;
}
});
Character codes:
37 - left
38 - up
39 - right
40 - down
You can use the keyCode of the arrow keys (37, 38, 39 and 40 for left, up, right and down):
$('.selector').keydown(function (e) {
var arrow = { left: 37, up: 38, right: 39, down: 40 };
switch (e.which) {
case arrow.left:
//..
break;
case arrow.up:
//..
break;
case arrow.right:
//..
break;
case arrow.down:
//..
break;
}
});
Check the above example here.
-
1I'm not sure about your use of the || operator in line 2. Isn't a value other than zero or nonzero implementation specific and not guaranteed? I would use something more like: var keyCode = (e.keyCode?e.keyCode:e.which); +1 for the use of the arrow object to give the cases readable names. – Mnebuerquo Apr 3 '10 at 22:58
-
6If you are using jQuery, you dont need to test for e.which:
The event.which property normalizes event.keyCode and event.charCode
- api.jquery.com/event.which – JCM Mar 6 '12 at 22:45 -
I'm trying to put a key event listener on a table, but it wouldn't work. Is there a limited amount of selector types that support key event listeners? – Arman Bimatov Oct 3 '13 at 21:24
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.
$(element).keydown(function(ev) {
if(ev.which == $.ui.keyCode.DOWN) {
// your code
ev.preventDefault();
}
});
-
2+1 for using the ui keycode object. Much easier to understand than 37, 38, 39, or 40. Not sure why the top answer is using e.keyCode when the jQuery documentation explicitly states to use e.which to account for browser differences. Hopefully this answer gets more recognition for doing it right. – J.Money Sep 3 '12 at 0:29
-
2Using $.ui.keyCode.DOWN on every key press is a LOT slower than using the number. Just add a comment if concerned about clarity, especially since it has to be run every time any key is pressed. – Jimbo Jonny Nov 24 '12 at 2:35
I've simply combined the best bits from the other answers:
$(document).keydown(function(e){
switch(e.which) {
case $.ui.keyCode.LEFT:
// your code here
break;
case $.ui.keyCode.UP:
// your code here
break;
case $.ui.keyCode.RIGHT:
// your code here
break;
case $.ui.keyCode.DOWN:
// your code here
break;
default: return; // allow other keys to be handled
}
// prevent default action (eg. page moving up/down)
// but consider accessibility (eg. user may want to use keys to choose a radio button)
e.preventDefault();
});
-
1Where is "ui" coming from? Getting " TypeError: $.ui is undefined " EDIT - I was missing JQuery UI. Got that loaded - no more error. – a coder Feb 8 '13 at 3:19
-
2He's apparently also using jQuery UI which must have that enum. I wouldn't include jQuery UI just for that, btw. – Jethro Larson Dec 4 '13 at 2:00
You can use KeyboardJS. I wrote the library for tasks just like this.
KeyboardJS.on('up', function() { console.log('up'); });
KeyboardJS.on('down', function() { console.log('down'); });
KeyboardJS.on('left', function() { console.log('right'); });
KeyboardJS.on('right', function() { console.log('left'); });
Checkout the library here => http://robertwhurst.github.com/KeyboardJS/
A terse solution using plain Javascript (thanks to Sygmoral for suggested improvements):
document.onkeydown = function(e) {
switch (e.keyCode) {
case 37:
alert('left');
break;
case 39:
alert('right');
break;
}
};
-
Probably also worth binding via
document.addEventListener('keydown', myFunction);
– nathanbirrell Dec 17 '17 at 5:09
Are you sure jQuery.HotKeys doesn't support the arrow keys? I've messed around with their demo before and observed left, right, up, and down working when I tested it in IE7, Firefox 3.5.2, and Google Chrome 2.0.172...
EDIT: It appears jquery.hotkeys has been relocated to Github: https://github.com/jeresig/jquery.hotkeys
-
I was reading where it said it was based on another library, and assumed that list of supported keys still applied. – Alex S Sep 10 '09 at 0:15
Instead of using return false;
as in the examples above, you can use e.preventDefault();
which does the same but is easier to understand and read.
-
4
return false;
ande.preventDefault();
are not exactly the same. See stackoverflow.com/a/1357151/607874 – Jose Rui Santos Mar 20 '12 at 10:47
Example of pure js with going right or left
window.addEventListener('keydown', function (e) {
// go to the right
if (e.keyCode == 39) {
}
// go to the left
if (e.keyCode == 37) {
}
});
You can use jQuery bind:
$(window).bind('keydown', function(e){
if (e.keyCode == 37) {
console.log('left');
} else if (e.keyCode == 38) {
console.log('up');
} else if (e.keyCode == 39) {
console.log('right');
} else if (e.keyCode == 40) {
console.log('down');
}
});
You can check wether an arrow key
is pressed by:
$(document).keydown(function(e){
if (e.keyCode > 36 && e.keyCode < 41) {
alert( "arrowkey pressed" );
return false;
}
});
prevent arrow only available for any object else SELECT, well actually i haven't tes on another object LOL. but it can stop arrow event on page and input type.
i already try to block arrow left and right to change the value of SELECT object using "e.preventDefault()" or "return false" on "kepress" "keydown" and "keyup" event but it still change the object value. but the event still tell you that arrow was pressed.
A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.
http://jaywcjlove.github.io/hotkeys/
hotkeys('right,left,up,down', function(e, handler){
switch(handler.key){
case "right":console.log('right');break
case "left":console.log('left');break
case "up":console.log('up');break
case "down":console.log('down');break
}
});
I came here looking for a simple way to let the user, when focused on an input, use the arrow keys to +1 or -1 a numeric input. I never found a good answer but made the following code that seems to work great - making this site-wide now.
$("input").bind('keydown', function (e) {
if(e.keyCode == 40 && $.isNumeric($(this).val()) ) {
$(this).val(parseFloat($(this).val())-1.0);
} else if(e.keyCode == 38 && $.isNumeric($(this).val()) ) {
$(this).val(parseFloat($(this).val())+1.0);
}
});
With coffee & Jquery
$(document).on 'keydown', (e) ->
switch e.which
when 37 then console.log('left key')
when 38 then console.log('up key')
when 39 then console.log('right key')
when 40 then console.log('down key')
e.preventDefault()