Event listener onkeydown issue Javascript - javascript

I am trying to create a hangman game, but my event listener doesn't seem as though it's working? When I press a key, there's no response from the webpage.
document.onkeydown = function (event) {
// If the game is finished, one keystroke will reset the game
if (hasFinished) {
resetGame();
hasFinished = false;
console.log("eventListenerWorking16");
} else {
// Make sure A-Z was actually pressed
if (event.keyCode >= 65 && event.keycode <= 90) {
makeGuess(event.key.toLowerCase());
updateDisplay();
checkWin();
checkLoss();
console.log("eventListenerWorking16");
}
}
};

Oh great .. One typo can takes hrs to resolve
One typo in this line
if (event.keyCode >= 65 && event.keycode <= 90) {
It has to be event.keyCode Caps not small

IMHO the event should fire correctly.
I think to make a better debug you should place a console.log right after the anonymous function call (see code below).
This way it will be possible to understand if there is something wrong after (that concerns the logic applied later).
document.onkeydown = function (event) {
console.log("keydown event fired");
// If the game is finished, one keystroke will reset the game
if (hasFinished) {
resetGame();
hasFinished = false;
console.log("eventListenerWorking16 hasFinished");
} else {
// Make sure A-Z was actually pressed
if (event.keyCode >= 65 && event.keycode <= 90) {
makeGuess(event.key.toLowerCase());
updateDisplay();
checkWin();
checkLoss();
console.log("eventListenerWorking16 makeGuess");
}
}
};

Try using this code:
document.addEventListener("keydown", myScript);

Related

Keypress is interfering with canv.onmousedown();

I'm trying to do two different actions when the canvas is clicked and when a key is pressed, but it seems like both can't be done at the same time. Is there a way to do this even if the functions are completely unrelated?
canv.onmousedown = function() {
console.log("Hello World");
};
And for keypress...
if(rightPressed && heroX < canvas.width) {
heroX += heroSpeed;
}
It can be done with single function. Listen for click event on canvas and check if it goes along with, for example shift being pressed.
function(e) {
if(!e.shiftKey) return; //it will do nothing unless shift key was pressed
}
You can do it for any button with e.keyCode property. For example e.keyCode === 32 would check if spacebar was pressed during the event. You can check any keyCode here.

Conditional debounce, depending on event.keyCode

I have a search field that takes user input and makes ajax requests using a debounced event listener.
html:
<input id="search" type="text"></input>
javascript:
function makeRequest() {
// make ajax request, do things with the information
}
$('#search').on('keypress', _.debounce(makeRequest, 200));
I need the event listener to not use the debounced ajax function on arrow up and down, that is event.keyCode === 38 or event.keyCode === 40
Is there a way to apply the advice from this question to my problem?
Make sure you save the results and only call the function, creating the function on every keypress creates an unnecessary overhead.
var debounced = _.debounce(makeRequest, 200);
$('#search').on('keypress', function(event) {
// just exit if it's an up or down arrow
if (event.which === 38 || event.which === 40) return;
debounced();
});
You just need to handle the keypress event in a different manner, where you can see the event properties.
Try this instead...
$('#search').on('keypress', function(event) {
// just exit if it's an up or down arrow
if (event.which === 38 || event.which === 40) return;
// do whatever you want here, knowing that up or down was not pressed.
});
Since your question is not about the debounce method you are trying to use, I've removed that from my example so you can focus on the specific issue that you are asking about.
The problem was that the callback to the event listener needs to call the function returned from _.debounce, not just create the debounced function.
$('#search').on('keypress', function(event) {
if (event.which === 38 || event.which === 40) {
// do other things
return;
}
_.debounce(makeRequest, 200)();
});

Key Navigation with Javascript

Please Help! I have spent a week to complete this game and this is the final huddle i have been stuck with for a couple of days now. I know some techy out there would probably take a glance and flick something in place. But I'm not very sophisticated with javascript and therefore need some help.
$(document).keydown(function(e){
// left arrow
if (e.keyCode == 37 && currentCell > 0) {
currentCell--;
ChangeCurrentCell();
return false;
}
// up arrow
if (e.keyCode == 38 && currentRow > 0) {
currentRow--;
ChangeCurrentCell();
return false;
}
// right arrow
if (e.keyCode == 39 && currentCell < MAX_CELL) {
currentCell++;
ChangeCurrentCell();
return false;
}
//down arrow
if (e.keyCode == 40 && currentRow < MAX_ROW) {
currentRow++;
ChangeCurrentCell();
return false;
}
// enter key
if (e.keyCode == 13) {
}
});
function ChangeCurrentCell()
{
document.getElementById(Boxes[currentRow + currentCell]).focus();
SimulateMouseOver(document.getElementById(Boxes[currentRow + currentCell]));
}
// function will trigger event of selecting current focus.
function selectElement()
{
}
$(document).ready(function(){
loadDivs()
// will give initial focus to top left element paving way for key navigation
ChangeCurrentCell();
// above gives first element in Boxes the focus when loading.
The div element will not focus despite getting it and calling the focus method, i have tried to trigger mousehover on the element with no luck. Please assist me, i put my masters thesis aside despite already being on a tight schedule to do this game which is a requirement for a job position. I have done whole the whole game logic and it all works well, if i send the code in as it is it will definitely be discarded because it doesnt meet the key navigation requirement ... i am desperate i will even pay if i need to -frustrated Student
Look at this
It's my solution for a test, maybe the same...maybe can help you :) If it is, please use it as a hint and don't copy all my code :D
Regards,
L.
You can bind to the document.keydown event to capture key strokes. Then you can use event.which (normalized by jQuery) to determine which key was pressed.
$(document).on("keydown", function (event) {
if (event.which === 37) {
//code for left arrow
} else if (event.which === 38) {
//code for up arrow
} else if (event.which === 39) {
//code for right arrow
} else if (event.which === 40) {
//code for down arrow
}
});
UPDATE
I just noticed you didn't tag your question with jQuery. To use native JS you'll have to change how you bind to the document.keydown event and how you determine the key that was pressed (different browser implementations store the info under different indexes of the event object).
to make it more convenient () not necessary:
`var LEFT = 37, UP = 38, RIGHT = 39, DOWN = 40, SPACE = 32;`
then bind to keydown, keypress doesn't catch arrow keys
and do something like this:
$(document).bind("keydown", function (e){
var which = e.which;
var navigationKeyWasPressed = which !== undefined && which >= 39 && which <= 40;
//do nothing if no significant key was pressed
if (!navigationKeyWasPressed ) {
return;
}
if ($(".selectedWithKey").length === 1){
switch (which) {
case LEFT:
//...
break;
case UP:
//...
break;
case RIGHT:
//...
break;
case DOWN:
//...
break;
case SPACE:
//turn card
break;
default: //non arrow pressed
//...
}
} else {
// if no card is selected, select one to start arrow navigation
$(".sponsor:first").addClass("selectedWithKey")
}
});

Stuck alt / modifier key with Javascript

I have a library that creates an editor on the fly (http://epiceditor.com) and also sets up key shortcuts automatically. The shortcuts can be configured in the options so I can't use e.altKey, e.ctrlKey, etc just a heads up.
For some reason the modifier key isn't being set back to false sometimes on Mac/Ubuntu browsers.
On Windows it seems to happen every time. You can reproduce this by clicking render in JSBin then pressing alt+p. You should see "Yay" appear. Now, if on Windows press just p again. You'll see "Yay appear again. Mac and Ubuntu users have seen this same issue occasionally but it's hard to reproduce it.
Also note this only happens with the alt key it seems. Below I have 16 (shift) next to the 18 (alt). If you swap those out it'll work as expected.
The code for the stripped down test case is:
var modKey = false;
var modKeyCode = 18; //16
document.body.addEventListener('keydown', function (e) {
if (!modKey && modKeyCode == e.keyCode) {
modKey = true;
}
if (modKey && e.keyCode == 80) {
console.log('Yay!');
}
});
document.body.addEventListener('keyup', function (e) {
if (modKey && modKeyCode == e.keyCode) {
modKey = false;
}
});
Demo: http://jsbin.com/uhupah/3/edit#javascript,html
I do not have access to my Linux box at the moment, so i cannot test your code.
Thus here is more of a suggestion:
Linux (in my experience) is finicky when it it comes to keyCodes and order of key events. Perhaps combine the if(..) from keyup with that of keydown
if (!modKey && modKeyCode == e.keyCode) {
modKey = true;
} else if (modKey && modKeyCode == e.keyCode) {
modKey = false;
}
The above suggestion is made with assumption that you have no specific requirement to have both 'keydown' and 'keyup'.
I've come up with a fix, albeit a sort of crappy fix, but a fix nonetheless.
The fix I went with was to reset the modifier var when any key combo was successful. I.e. one the p in alt+p is pressed reset the modKey to false like this:
var modKey = false;
var modKeyCode = 18; //16
document.body.addEventListener('keydown', function (e) {
if (!modKey && modKeyCode == e.keyCode) {
modKey = true;
}
if (modKey && e.keyCode == 80) {
console.log('Yay!');
modKey = false; //THIS
}
});
document.body.addEventListener('keyup', function (e) {
if (modKey && modKeyCode == e.keyCode) {
modKey = false;
}
});
The problem with this tho is that you can't do back to back key commands. Most of the time this is alright because the user will do a key command like "save" or "preview" or something, type some more, then do another key command. But you wouldn't be able to, let's say: alt+p s to trigger alt+p then alt+s without having to let go of the alt key.

how to re-enable default after doing event.preventDefault()

I know this exact question was asked here, but the answer didn't work for what I needed to do so I figured I'd give some example code and explain a bit...
$(document).keypress(
function (event) {
// Pressing Up or Right: Advance to next video
if (event.keyCode == 40 || event.keyCode == 39) {
event.preventDefault();
$(".current").next().click();
}
// Pressing Down or Left: Back to previous video
else if (event.keyCode == 38 || event.keyCode == 37) {
event.preventDefault();
$(".current").prev().click();
}
}
);
It basically disables the arrow keys to use them for something else, but doing:
$(document).keypress(function () { });
doesn't enable the default function again... I need it to scroll the page without having to create a scroll function for it...
Any ideas?
Thanks,
Matt
Adding a new handler doesn't replace the previous one, it adds a new one. You may be looking for jQuery#unbind if you're trying to remove the previous handler, but if you're going to be turning this on and off a lot, you probably would be better off with a flag telling you whether to prevent the default or not in your existing handler.
Adding, and later removing, a handler looks like this:
function keypressHandler() { /* ... */};
$('#thingy').keypress(keypressHandler);
// ...elsewhere...
$('#thingy').unbind('keypress', keypressHandler);
I'm not sure this is the right way to handle it.
A better way to approach this problem would be to put some kind of check inside your document.keypress instructions.. like..
var enableKeys = false;
$(document).keypress(
function (event) {
// Pressing Up or Right: Advance to next video
if (event.keyCode == 40 || event.keyCode == 39 && enableKeys) {
event.preventDefault();
$(".current").next().click();
}
// Pressing Down or Left: Back to previous video
else if (event.keyCode == 38 || event.keyCode == 37 && enableKeys) {
event.preventDefault();
$(".current").prev().click();
}
}
);
Then control the enablekeys wherever you feel necessary, either with a hover, or something along those lines.
function(e){ e.preventDefault(); }
and its opposite
function(e){ return true; }
Why not just wrap a condition around event.preventDefault(); in your current code?
Try to unbind the keypress event from document.
I don't know of any other ways to do it.
HTH

Categories