I want to fire a javascript function called 'faster' whenever the period key is pressed. I first tried a method which had worked for other keys:
document.onkeydown = function(evt) {
evt.preventDefault();
evt = evt || window.event;
switch (evt.keyCode) {
case 190:
faster();
break;
}
};
I also tried this with the code 46, but still no luck. One post said that Mac keyboards are less reliable and suggested using onkeypress instead of onkeydown. I couldn't find a directly relevant example, but I tried this:
JavaScript
periodetect () {
var c = e.which || e.keyCode;
if (c=46) {
faster();
}
};
HTML
<BODY BGCOLOR="#CCCCCC" onkeypress="periodetect()">
Can anyone spot my beginner mistake or suggest alternative?
This might be the solution you are looking for:
Requires jquery 1.9.x or later
$(document).bind('keydown',function(e){
if(e.keyCode == 190) {
alert("you pressed .");
}
});
When you press the "period key" and alert will show, if you want it with a function just replace alert("you pressed ."); with faster();
Test it yourself: http://jsfiddle.net/d60jtqdc/
It turns out that keydown appears to be the right thing to use after all. It also turns out that keyCode is not capitalized in the OP's code given in the comment to my answer, but is correctly capitalized in the question. The examples below do work now that I've changed the first one.
Have a look at this: onKeyPress Vs. onKeyUp and onKeyDown
document.onkeydown = function(evt) {
evt.preventDefault();
evt = evt || window.event;
switch (evt.keyCode) {
case 190:
faster();
break;
}
};
Edited to add: Can someone test this code in a Mac, please?
<!DOCTYPE html>
<html>
<head>
<title>Stack Overflow Tester</title>
<style type="text/css">
</style>
<script type="text/javascript">
//<![CDATA[
document.onkeydown = function(evt) {
evt.preventDefault();
evt = evt || window.event;
switch (evt.keyCode) {
case 190:
alert("Faster!");
break;
}
};
//]]>
</script>
</head>
<body>
<p>Stack Overflow Test; press the period.</p>
</body>
</html>
I have a problem with javascript keys, Chrome (only testing on chrome right now) does not recognise up and down arrows on text input, as it has this default behaviour in which it changes the caret position.
My code is as follows:
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13'){ //enter key
//some code that works
return false;
}else if(keyCode=='38'){ //up key
//some other code that doesn't work
return false;
}else if(keyCode=='40'){ //down key
//some other code that doesn't work
return false;
}
If anyone has a solution I will greatly appreciate it.
Thank you!
Hard to see where the code is from (an keypress listener I guess).
As you can see below and this fiddle (and as Teemu also pointed out), keypress won't get called on arrow keys.
On another note, use event.preventDefault() to prevent the default behaviour of the browser, in your case the placing of the caret, also your listener functions can except an event object as a parameter.
var listener = function (e) {
e = e || window.event;
alert(e.type);
var keyCode = e.keyCode || e.which;
if(keyCode=='38' || keyCode=='40'){ //arrow key
alert("arrow!");
e.preventDefault();
return false;
}
}
var elem = document.getElementById('input');
elem.addEventListener('keydown', listener, false);
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).
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()