Javascript keycode clash: "right arrow" and "single quote" - javascript

The following script does what it should, that is, it reacts on the keys "arrow left" and "arrow right". However, due to a keycode clash, it reacts on a single quote as well. It makes it impossible to enter that character into an input field. Can anything be done about that?
<script type="text/javascript">
onload = function(){
document.onkeypress=function(e){
if(window.event) e=window.event;
var keycode=(e.keyCode)?e.keyCode:e.which;
switch(keycode){
case 37: window.location.href='set.jsp?index=5';
break;
case 39: window.location.href='set.jsp?index=7';
break;
}
}
}
</script>

When the user presses the single quote key, the e.keyCode property is zero, and the e.which property is 39. Executing String.fromCharCode(39) returns a single quote.
You want the keyCode if that property is in the event object:
var keycode = "keyCode" in e ? e.keyCode : e.which;
That way you get zero for the keyCode when that property exists in the event object, and when the which property also exists.
document.onkeydown = function(event) {
event = event || window.event;
var keyCode = "keyCode" in event ? event.keyCode : event.which;
switch (keyCode) {
case 37: console.log("37 was pressed", event); break;
case 39: console.log("39 was pressed", event); break;
}
};
Edit #1: Other commenters and answers are correct. I forgot you shouldn't be detecting control keys with keypress events. Changed to onkeydown.
Full HTML example that works cross browser:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Key Codes Test</title>
</head>
<body>
<script type="text/javascript">
document.onkeydown = function(event) {
event = event || window.event;
var keyCode = "keyCode" in event ? event.keyCode : event.which;
switch (keyCode) {
case 37: console.log("37 was pressed", event); break;
case 39: console.log("39 was pressed", event); break;
}
};
</script>
<input type="text" size="30">
</body>
</html>

keypress should not capture control keys like left/right arrow. if you use keydown event, single quote keycode is 222 definitely no conflict

As it is a text input, it seems you'd also have a problem when someone is trying to use the arrow keys to move the cursor within the input. Thus, stopping event propagation/bubbling should be used, and can solve the main issue you're asking about.
// assuming you've grabbed an input in var input_ele
input_ele.onkeypress = function (e) {
e = e || window.event;
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
};
Using this will stop the keypress event from leaving the input element, thereby never reaching the document element to trigger the unwanted behavior. In other words, you don't break the expected behavior of a very standard control element.

Use keydown instread of keypress
jS:
document.onkeydown=function(event){
if(window.event) event=window.event;
var keycode=(event.keyCode)?event.keyCode:event.which;
switch(keycode){
case 37: alert("an arrow");
break;
case 39: alert("another arrow");
break;
}
}
Fiddle : http://jsfiddle.net/p9x1Lj4u/2/

Related

Execute JavaScript function when period key pressed

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>

JavaScript: Using up and down arrows on input text

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);

Go to link when pressing keyboard arrows

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

Bind Multiple Keys to Keypress Event

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).

Binding arrow keys in JS/jQuery

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()

Categories

Resources