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.
document.onkeydown = 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)
};
If you need to support IE8, start the function body as e = e || window.event; switch(e.which || e.keyCode) {.
(edit 2020)
Note that KeyboardEvent.which is now deprecated. See this example using KeyboardEvent.key for a more modern solution to detect arrow keys.
$(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.
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();
}
});
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();
});
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;
}
};
Also see https://stackoverflow.com/a/17929007/1397061.
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
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.
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');
}
});
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 check wether an arrow key is pressed by:
$(document).keydown(function(e){
if (e.keyCode > 36 && e.keyCode < 41) {
alert( "arrowkey pressed" );
return false;
}
});
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
}
});
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.
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()
Related
I am trying to disable arrow up and down function for a selection list field. I have searched and tried all the options but could not disable. When alerting with the keys it is working but when I try to disable it does not work. Is there any updates related with browsers
My Chrome Version: 89.0.4389.128 (Official Build) (64-bit)
// we are closing the arrow keys for selection
$(function()
{
$('.form-contact').on('keyup',function(e) {
if(e.keyCode === 38 || e.keyCode === 40) { //up or down
// alert(e.keyCode)
e.preventDefault();
return false;
}
});
});
Last code something like this. it does not prevent arrow up or down to the list but it prevents selection by enter from the list. So better than nothing. Still open my question.
$('.form-contact,.form-company,.form-address,.form-postcode,.form-phone,.form-email').on('keydown', (e) => {
if (e.target.localName != 'input') { // if you need to filter <input> elements
switch (e.keyCode) {
case 38: // up
case 40: // down
e.preventDefault();
break;
default:
break;
}
}
}, {
capture: true, // this disables arrow key scrolling in modern Chrome
passive: false // this is optional, my code works without it
});
Instead of keyup, use keydown event
$(function()
{
$('.form-contact').on('keydown',function(e) {
if(e.keyCode === 38 || e.keyCode === 40) { //up or down
// alert(e.keyCode)
e.preventDefault();
return false;
}
});
});
This might be helpful:
window.addEventListener("keydown", function(e) {
if(["Space","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].indexOf(e.code) > -1) {
e.preventDefault();
}
}, false);
Found it here Disable arrow key scrolling in users browser
I want to eventing more keys in my Javascript code:
<script>
function OPEN(e) {
if (e.type !== "blur") {
if (e.keyCode === 70) {
alert("Pressed F");
}
}
}
document.onkeydown = OPEN;
</script>
What I am getting from your question is that you want to detect more keys presses. The best way to detect key presses is a switch statement
function OPEN(e) {
if (e.type !== "blur") {
switch (e.keyCode) {
case 70:
alert("Pressed F");
break;
case 65:
alert("Pressed A");
break;
default:
alert("I don't know what to do with that key!");//This line is removable
break;
}
}
}
document.onkeydown = OPEN;
How it works
The way a switch works is:
switch (VALUE) {
case THIS_VALUE:
CODE
break;
default:
CODE
break;
}
That was probably the worst explanation you've seen so you can read about here
Without keyCode
keyCodes are kind of irritating to figure out, you can use:
function OPEN(e) {
if (e.type !== "blur") {
switch (String.fromCharCode(e.keyCode)) {
case "F":
alert("Pressed F");
break;
case "A":
alert("Pressed A");
break;
case "B":
alert("Pressed B");
default:
alert("I don't know what to do with that key!");//This line is removable
break;
}
}
}
document.onkeydown = OPEN;
Detect Key Combinations
When detecting key combinations, you can use && to make sure both key's are pressed. Without some more complicated. You can use:
e.metaKey Window key on Windows, Command Key on Mac
e.ctrlKey Control key
e.shiftKey Shift key
e.altKey Alt key
Use them as:
if (e.ctrlKey && e.keyCode === 65) {
alert("Control and A key pressed");
}
To detect all keys are currently pressed (multiple) I found this fiddle (not mine), and a question here
may be that make what you want
<script>
function OPEN(event) {
var x = event.which || event.keyCode;
alert( "The Unicode value is: " + String.fromCharCode(x));
// The Unicode value is: a
//The Unicode value is: b
}
</script>
then add this attr to your body
<body onkeydown="OPEN(event)">
If you're not opposed to using a library for this, I find Mousetrap.js to be awesome and very easy to use.
Here are a few examples from the link above:
<script>
// single keys
Mousetrap.bind('4', function() { console.log('4'); });
Mousetrap.bind("?", function() { console.log('show shortcuts!'); });
Mousetrap.bind('esc', function() { console.log('escape'); }, 'keyup');
// combinations
Mousetrap.bind('command+shift+k', function() { console.log('command shift k'); });
// map multiple combinations to the same callback
Mousetrap.bind(['command+k', 'ctrl+k'], function() {
console.log('command k or control k');
// return false to prevent default browser behavior
// and stop event from bubbling
return false;
});
// gmail style sequences
Mousetrap.bind('g i', function() { console.log('go to inbox'); });
Mousetrap.bind('* a', function() { console.log('select all'); });
// konami code!
Mousetrap.bind('up up down down left right left right b a enter', function() {
console.log('konami code');
});
</script>
I am using the JQuery UI Dialog to create a pop-up. The pop-up has two buttons. The first button is automaticly selected by JQuery. I can change the selection between the buttons and the exit button with 'tab'.
I want to change the selection (only between the two buttons) also with the left and right arrow keys on the keyboard.
Where do I have to catch the arrow key down events and how can I change the focus of the buttons?
Thanks for your help!
I would do it something like that :)
$('body').on('keydown', '#terug', function(e) {
if (e.keyCode === 39) { //right arrow
$('#ok').focus();
}
});
$('body').on('keydown', '#ok', function(e) {
if (e.keyCode === 37) { //left arrow
$('#terug').focus();
}
});
Try it :) And if this won't work then go global without specifying selector in event definition:
$('body').on('keydown', function(e) {
if (e.keyCode === 39 && $('#terug').is(':focus')) { //right arrow
$('#ok').focus();
}
});
Hope this will help! :) If not give me a comment and i will try to fix this. :)
Thanks for your help! It worked. I added my solution to complete this question.
I bind the keydown event only on the ui-buttons:
$(document).on('keydown', '.ui-button', handleUIButtonKeyDown);
After that I handle the left and right arrow keys
function handleUIButtonKeyDown(event) {
if (event.keyCode == 37) {
//left arrow key pressed, select the previous button
makeButtonFocus($(this).prev(".ui-button"));
} else if (event.keyCode == 39) {
//right arrow key pressed, select the next button
makeButtonFocus($(this).next(".ui-button"));
}
}
function makeButtonFocus($button) {
$button.addClass("ui-state-focus");
$button.focus();
}
Here's a more generic answer
works on any number of buttons irregardless of DOM structure (btns need not be siblings)
$('body').on('keydown', function(e) {
if (e.keyCode === 37) { //left arrow
modalKeyboardNav("prev")
} else if (e.keyCode === 39) { //right arrow
modalKeyboardNav("next");
}
});
function modalKeyboardNav(dir) {
if (!$("body").hasClass("modal-open")) {
// no modal open
return;
}
var $curModal = $(".modal.show"),
$curFocus = $(document.activeElement),
$focusable = $curModal.find(".btn"),
curFocusIdx = $focusable.index($curFocus);
if (curFocusIdx < 0) {
// nothing currently focused
// "next" will focus first $focusable, "prev" will focus last $focusable
curFocusIdx = dir == "next" ? -1 : 0;
}
if (dir == "prev") {
// eq() accepts negative index
$focusable.eq(curFocusIdx - 1).focus();
} else {
if (curFocusIdx == $focusable.length - 1) {
// last btn is focused, wrap back to first
$focusable.eq(0).focus();
} else {
$focusable.eq(curFocusIdx + 1).focus();
}
}
}
I have 2 links: <a href='leftLink.php'><< Prev</a> and <a href='rightLink.php'>Next >></a>.
Can it be possible to go to leftLink when pressing left arrow from keyboard, and to rightLink.php when pressing right arrow from keyboard? Any advice would be very welcome
Thank you in advance.
You can setup a keyboard event listener (keydown or keyup) on the document.
document.addEventListener('keydown',(event)=>{});
Check the key property (modern browsers) or keyCode (deprecated, older browsers) on the event object for the appropriate value corresponding to the left and right arrows.
switch(event.key){
case 'ArrowLeft':
break;
case 'ArrowRight':
break;
}
Then use the click() method of the respective link to trigger the navigation.
document.getElementById("prevLink").click();
let prevLink = document.getElementById("prevLink");
let nextLink = document.getElementById("nextLink");
document.addEventListener("keydown", ({key}) => {
switch (key) {
case 'ArrowLeft':
console.log('Left arrow');
prevLink.click();
break;
case 'ArrowRight':
console.log('Right arrow');
nextLink.click();
break;
}
});
<a id="prevLink" href='#prevUrl'><< Prev</a>
<a id="nextLink" href='#nextUrl'>Next >></a>
Use this to detect keypress..
function checkKey(e) {
var event = window.event ? window.event : e;
if (true) {
alert(event.keyCode)
}
}
from here determine the key pressed and use document.location to redirect the browser.
keycodes are:
left = 37
up = 38
right = 39
down = 40
You can try this:
$("body").keydown(function(e) {
if(e.keyCode == 37) { // left
//your code
window.location.href = "leftLink.php";
}
else if(e.keyCode == 39) { // right
//your code
window.location.href = "rightLink.php";
}
});
Reference
I am currently using this Javascript keypress code to fire events upon keypress:
$(document).keydown(function(e) {
switch(e.keyCode) {
case 39:
e.preventDefault();
alert("Arrow Key");
break;
case 37:
e.preventDefault();
alert("Arrow Key");
}
});
but what I am wondering is if I can instead of binding one key bind a combination of two keys. Could I possibly do something like:
$(document).keydown(function(e) {
switch(e.keyCode) {
case 39 && 37:
e.preventDefault();
alert("Arrow Key");
break;
}
});
If you want to check multiple keys at once you should only use one regular key and one or more modifier keys (alt/shift/ctrl) as you cannot be sure that two regular keys can actually be pressed at once on the user's keyboard (actually, they can always be pressed but the PC might not understand it due to the way keyboards are wired).
You can use the e.altKey, e.ctrlKey, e.shiftKey fields to check if the matching modifier key was pressed.
Example:
$(document).keydown(function(e) {
if(e.which == 98 && e.ctrlKey) {
// ctrl+b pressed
}
});
Why not use if rather than switch?
$(document).keydown(function(e) {
if ((e.keyCode === 37) || (e.keyCode === 39)) {
e.preventDefault();
alert("Arrow Key");
}
});
You can use the case fallthrough:
$(document).keydown(function(e) {
switch(e.which) {
case 39:
case 37:
e.preventDefault();
alert("Arrow Key");
break;
}
});
Note that I'm using e.which instead of e.keyCode to make it work in all browsers (jQuery automatically assigns the property which actually contains the key code to e.which).