I have a key press event listener on all direction keyboard keys which is setup when the page loads. I want to disable this event listener when the user reaches the finish line on my maze game. I have attempted to do this (see code below) but when the user reaches the finish line, the event listener remains active and the user can continue to move around the maze.
I would like to do this just using vanilla javascript. Any suggestions you have would be greatly appreciated.
Here is the event listener:
document.addEventListener("keydown", moveCharacter = (e) => {
let currentPos = naviCtrl.currentPosition(DOMstrings.boxes, DOMstrings);
document.querySelector(DOMstrings.timer).innerHTML = "";
const key_code = e.which || e.keyCode;
switch (key_code) {
case 37: //left arrow key
naviCtrl.moveLeft(currentPos, chosenCharacter);
playerCtrl.playerFinished();
break;
case 38: //Up arrow key
naviCtrl.moveUp(currentPos, chosenCharacter);
playerCtrl.playerFinished();
break;
case 39: //right arrow key
// naviCtrl.removeCharacter(DOMstrings);
naviCtrl.moveRight(currentPos, chosenCharacter);
playerCtrl.playerFinished();
break;
case 40: //down arrow key
naviCtrl.moveDown(currentPos, chosenCharacter);
playerCtrl.playerFinished();
break;
}
});
Here is what I have tried:
playerFinished: (currentPos) => {
if (document.querySelector(DOMstrings.characterImg).parentNode.id === 36 || document.querySelector(DOMstrings.characterImg).parentNode.id === "box-36") {
//1. stop player movement
document.removeEventListener("keydown", appController.moveCharacter);
}
},
Use document.removeEventListener("keydown", moveCharacter); since you defined moveCharacter and not navigationController.moveCharacter.
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>
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/
I am trying to implement a keyboard shortcut for my application. I want to use ALT + Q combination. However, when I try to run the code and press ALT key, it sets focus on the browsers menu bar control and it fails.
I tried to stop event propagation by several methods like,
function KeyDownEventHandler() {
if (event.keyCode == 18) {
//stop code
}
}
stopPropagation(event);
CancleBubbling();
return false;
event.preventDefault();
Still it behaves the way.
EDIT - Actually the problem is not with detection. When user press ALT key and release it and Q key is pressed after that, it highlights browser menu. It doesn't call function for custom shortcut.
Is it the default behaviour of the browser ? Can we override it ?
Please help in the same.
Thanks
UPDATE
Here is a fiddle detecting exactly "ALT+Q" sequence:
document.onkeydown = KeyCheck;
var previousKeyCode = 0;
function KeyCheck(e) {
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch (KeyID)
{
case 18:
previousKeyCode = 18;
break;
case 81:
if (previousKeyCode == 18) {
alert("ALT+Q Pressed!!!")
}
previousKeyCode=KeyID;
break;
default: previousKeyCode=KeyID;
}
}
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()