Javascript keycode clash: "right arrow" and "single quote"
The following script does what it should, that is, it responds to the left arrow and right arrow keys. However, due to a collision with a combination lock, he also reacts to one quote. This makes it impossible to enter this character in the input field. Is there anything you can do about this?
<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>
source to share
When the user presses the single quote key, the property e.keyCode
is zero and the property e.which
is 39. Execution String.fromCharCode(39)
returns one quote.
You want keyCode
if this property is in the event object:
var keycode = "keyCode" in e ? e.keyCode : e.which;
So you get zero for keyCode when that property exists on the event object and when the property which
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 that you shouldn't be able to detect event control keys keypress
. Changed to onkeydown
.
Full HTML example that works in a 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>
source to share
Just like text input, it seems like you will also have a problem when someone tries to use the arrow keys to move the cursor inside the input. So, you should use event propagation / bubbling stop and solve the underlying problem you are asking for.
// 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 cause the event keypress
not to leave the input element, thus never reaching the document element to trigger unwanted behavior. In other words, you are not breaking the expected behavior of a very standard control.
source to share
Use keydown
instread forkeypress
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/
source to share