I'm trying to execute some code when multiple buttons are pushed, I'm trying this as an example but it's not working :
<script>
var map = {82: false, 84: false};
function keydown(e) {
if (e.keyCode in map) {
map[e.keyCode] = true;
if (map[82] && map[84]) {
alert(" all pressed ");
}
}
}
function keyup(e)
{
if (e.keyCode in map) {
map[e.keyCode] = false;
}
}
window.addEventListener('keyup', keyup);
window.addEventListener('keydown', keydown);
</script>
I get the alert even when only one button is pushed, ( i got it when both are pushed too )
What am i doing wrong please ?
You don't seem to be attaching your keyup handler, so once a key has been pressed it was forever marked as true in your map
window.addEventListener('keyup', keyup);
Try this:
var map = [];
onkeydown = onkeyup = function(e){
e = e || event; // to deal with IE
map[e.keyCode] = e.type == 'keydown';
if(map[82] && map[84]){
alert('all pressed');
}
}
This was also already answered here:
JavaScript multiple keys pressed at once
Please make sure you check to avoid posting a duplicate question.
I think I found the problem, the program doesn't execute the keyup fonction because of the alert, map[82] and map[84] are always true then.
Related
I have the following code:
undoButton.onclick = undoFunction;
document.addEventListener("keydown", (e) => {
if ((e.ctrlKey || e.metaKey) && e.code === "KeyZ") {
e.preventDefault();
undoFunction();
}
});
function undoFunction() {
console.log("undo function...");
}
When I click the button, as excepted, the function code runs once, and so does the console.log, but when I use the key stroke, the function is running a multiple times, up to hundreds of so-called loops at some scenarios. Any suggestion why? I tried to used e.repeat = false but had no luck. Thanks!
Use keyup instead. The keydown event triggers as long a key is hold down. keyup only triggers when a key is released.
var undoButton = document.getElementById('undoButton');
undoButton.onclick = undoFunction;
document.addEventListener("keyup", (e) => {
if ((e.ctrlKey || e.metaKey) && e.code === "KeyZ") {
e.preventDefault();
undoFunction();
}
});
function undoFunction() {
console.log("undo function...");
}
<input id="undoButton" type="button" value="Undo" />
First, I would like to thank all for your help and replies.
I'm working on a project that required users to press a key and hold it, it will trigger an action.
When the user presses another key ( still holing the first key), it will trigger another action.
However, I'm stuck getting JavaScript to recognize two keys being pressed at the same time.
var down = false;
var keys;
document.addEventListener("keydown", function (e) {
if (down) {return;}
down = true;
keys = (keys || []);
keys[e.keyCode]=true;
if (keys[87]){
console.log("1");
}
else if (keys[83]){
console.log("2");
}
else if (keys[83] && keys[87]){
console.log("sucessfull");
}
} , false);
document.addEventListener("keyup", function (e) {
down = false;
keys[e.keyCode]=false;
stop();
}, false);
<button id="up" onmousedown="Drive(1)" onmouseup="Drive(2)">UP </button>
Removed the 'down' variable checks
Removed the mouse button element thing - didn't seem relevant to your problem?
Removed the extra HTML body
Got rid of the else branching as it would be satisfied (by 87 or 83) before ever getting to the && condition
var keys;
document.addEventListener("keydown", function (e) {
keys = (keys || []);
keys[e.keyCode]=true;
if (keys[87]){
console.log("1");
}
if (keys[83]){
console.log("2");
}
if (keys[83] && keys[87]){
console.log("sucessfull");
}
} , false);
document.addEventListener("keyup", function (e) {
keys[e.keyCode]=false;
stop();
}, false);
Well I searched on Google but still didn't found the answer I was looking for.
I want to check if the user pressed a key, something like this -
if(document.onkeyup) {
// Some Stuff here
}
I know I can do this, this way -
document.onkeyup = getKey;
But the function getKey cannot return values.
So how can I check if the user pressed a key?
EDIT : I need pure Javascript for this thing..
You can do this in pure Javascript using the event object, without the need of external libraries such as jQuery.
To capture the keycode, just pass the event as parameter of getKey function:
function getKey(e)
{
window.alert("The key code is: " + e.keyCode);
}
document.onkeyup = getKey;
Frequently used keyCode list:
For a usefull list of keyCodes, you can check out this URL:
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Setting the keyCode to a global variable:
If you are interested in capturing the keyCode for later usage, you can do something like this:
var keycode = "";
(...)
function getKey(e)
{
keycode = e.keyCode;
}
document.onkeyup = getKey;
window.alert("The key code is: " + keycode);
Setting the keyCode to the event source object:
If you don't like global variables, like me, you could also do something like this:
function getKey(e)
{
keycode = e.keyCode;
var objectFromEvent = e.currentTarget ? e.currentTarget : event.srcElement;
objectFromEvent.customProperty = keycode;
}
document.customProperty = "";
document.onkeyup = getKey;
// now the value is in the "customProperty" of your object =)
window.alert("The key code is: " + document.customProperty);
One way you could do it is using variables
and then you could check that variable some were else...
for example
var keypressed = "";
document.onkeyup = function(e){
if (typeof event !== 'undefined') {
keypressed = event.keyCode;
}
else if (e) {
keypressed = e.which;
}
return false; // Prevents the default action
}
You really should not be doing this but if you really must:
var getKey = (function () {
var currentKey = null;
document.onkeyup = function (event) {
// determine the pressed key (across browsers)
// by inspecting appropriate properties of `event`
// and update currentKey; E.g:
currentkey = event.which ? event.which : window.event.keyCode;
}
return function () {
return currentkey;
}
})();
This will give you the last key user pressed.
If you need to get the currently pressed key (until released) then you need to attach keydown event to update currentKey variable and keyup event to set it to null.
You have to attach the event to the window global object and to set a function that listen to the event.
This sample show you how to track the keyup and keydown events.
window.addEventListener('keydown', onKeyDown, true);
window.addEventListener('keyup', onKeyUp, true);
function onKeyDown(evt) {
// key up event as been fired
console.log(evt.keyCode);
}
function onKeyUp(evt) {
// key up event as been fired
console.log(evt.keyCode);
}
See element.addEventListener on MDN for more details.
I would use jquery and do something like this:
// arrow keys click
$(document).keyup(function(e) {
// left arrow
if (e.keyCode == "37" ) {
// left stuff
// right arrow
} else if (e.keyCode == "39") {
// right stuff
// up arrow
} else if (e.keyCode == "38") {
// up stuff
// down arrow
} else if (e.keyCode == "40") {
// down stuff
}
});
etc, for the different key codes seen here http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
If you are attempting to run an event to test when a certain key is pressed, you can use this.
document.addEventListener('keydown', function(event) {
var key_code = event.keyCode;
if (key_code === 38) {
alert('test);
}
});
so right now I'm using a function that will set a value to true if one key being pressed, another being pressed regardless of whether or not the first one is still depressed.
function doc_keyUp1(e) {
if (e.keyCode == 37){
lPunch = true
}
}
function doc_keyUp2(e) {
if (e.keyCode == 39){
rPunch = true
}
}
document.addEventListener('keyup', doc_keyUp1, false)
document.addEventListener('keyup', doc_keyUp2, false)
The thing is, I want to be able to have it make sure that if the second key is being pressed, that the first one must still be down, so that someone can't just press one then the other quickly and make it seem as if they were both pressed down at the same time.
Any ideas?
Assuming you have some kind of "game loop" something like the following works (or perhaps I should say "should work", in that I haven't coded something like this for a long time and so haven't tested it with current browsers - definitely used to work):
var keyPressed = {};
document.addEventListener('keydown', function(e) {
keyPressed[e.keyCode] = true;
}, false);
document.addEventListener('keyup', function(e) {
keyPressed[e.keyCode] = false;
}, false);
function gameLoop() {
if (keyPressed["39"] && keyPressed["37"]) {
// do something (update player object state, whatever)
}
// etc
// update display here
setTimeout(gameLoop, 5);
}
gameLoop();
I'd suggest you use an Array to hold key states.
var keyStates = [ ];
document.addEventListener('keydown', function(e) {
keyStates.push( e.keyCode );
}, false);
document.addEventListener('keyup', function(e) {
var pos = null;
if( (pos = keyStates.indexOf( e.keyCode )) > -1 )
keyStates.splice( pos, 1 );
}, false);
So with that, you can always check that array for keys currently beeing pushed.
var currentKeyCodes=new Object();
function keyDown(e) {
currentKeyCodes['x'+e.keyCode]=true;
}
function keyUp(e) {
//Real check here
if ((e.keyCode==39) && currentKeyCodes['x37']) {
do_whatever_you_want();
}
//Housekeeping
var s='x'+e.keyCode;
if (currentKeyCodes[s]) currentKeyCodes[2]=false;
}
I have a javascript window.open popup, and I want the popup to close itself when the user presses the ESC key. I can't figure out how to hook the keydown event (and on what object?) so that I can catch the ESC key.
I'm using jQuery.
Try something like this:
$(document).keydown(function(e) {
// ESCAPE key pressed
if (e.keyCode == 27) {
window.close();
}
});
It is possible to achieve with JS Without using jQuery.
window.onkeydown = function( event ) {
if ( event.keyCode == 27 ) {
console.log( 'escape pressed' );
}
};
event.key === "Escape"
No more arbitrary number codes!
document.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; in ES6+
if (key === "Escape") {
window.close();
}
});
Mozilla Docs
Supported Browsers
Remember that you must use the function #Gumbo posted in the popup-window... So you will need to include JQuery in the popup and execute the function there, not the window that opens the popup.
To handle both esc and enter key on dialog
window.onkeydown = function(event) {
if(event.keyCode===27|| event.keyCode===13){
window.close();
}
}
You can easily achieve bind key events using Jquery.
Here you can use .keydown()
List of keyboard keys codes
$(document).keydown(function(e) {
if (e.keyCode == 27) {
window.close();
}
});
#Gumbo 's answer is good but often you need to unhook this behaviour so I suggest to use the one event handler:
$(document).one('keydown', function(e) {
// ESCAPE key pressed
if (e.keyCode == 27) {
window.close();
}
});
OR
$(document).on('keydown', function(e) {
// ESCAPE key pressed
if (e.keyCode == 27) {
window.close();
}
});
and when ready to stop the behaviour
$(document).off('keydown');
In case if any looking for angularjs popup solution here you go
*this is without using ui-bootstrap dependency(only recommended when there is no other way)
$scope.openModal = function(index){
$scope.showpopup = true;
event.stopPropagation();//cool part
};
$scope.closeModal = function(){
$scope.cc.modal.showpopup = false;
};
window.onclick = function() {
if ($scope.showpopup) {
$scope.showpopup = false;
// You should let angular know about the update that you have made, so that it can refresh the UI
$scope.$apply();
}
};
//escape key functionality playing with scope variable
document.onkeydown = function (event) {
const key = event.key; // const {key} = event; in ES6+
if (key === "Escape") {
if ($scope.showpopup) {
$scope.showpopup = false;
// You should let angular know about the update that you have made, so that it can refresh the UI
$scope.$apply();
}
}
};
References: above answers and http://blog.nkn.io/post/hiding-menu-when-clicking-outside---angularjs/