Key Navigation with Javascript - 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")
}
});

Related

css HTML gallery react to keyboard

I recently made a rudimentary html/css galery that is practicaly a table with next/previous buttons.The thing is I want to make it responsive to keyboard.Like if anyone hits the "left" button on keyboard it should go on the previous photo and if it hits the "right" button go on the next page.
I would love if you could make it with as less javascript/jquery as possible.I searched google for something like that but I haven't found none !
If you need any code of my website please let me know.
Please help !
You could capture the keyboard interaction using .on() and the keydown event, and decide what to do after the returned value like :
$(document).on("keydown", function (e) {
e.preventDefault();
var code = e.which || e.keyCode;
console.log(code)
if (code == 40) {
// down arrow pressed : do something
console.log("down arrow pressed")
}
});
See JSFIDDLE
The keyboard map of the navigation arrows are
// 37 = left arrow
// 38 = up arrow
// 39 = right arrow
// 40 = down arrow
EDIT : to avoid excessive use of if else if else, you could use switch (which performs better) like :
$(document).on("keydown", function (e) {
e.preventDefault();
var code = e.which || e.keyCode;
switch (code) {
case 37:
console.log("left arrow pressed")
break;
case 38:
console.log("up arrow pressed")
break;
case 39:
console.log("right arrow pressed")
break;
case 40:
console.log("down arrow pressed")
break;
default:
return false
}
});
See updated JSFIDDLE
JFK's answer is correct, but I extended that a little
$(document).on("keydown", function (e) {
var code = e.which || e.keyCode;
if (code == 40 || code == 39) { // down & right
// replace selector with your button id/class
$('.btn-next').click();
} else if (code == 38 || code == 37) { // up & left
// replace selector with your button id/class
$('.btn-previous').click();
}
});
The code simulates a click on the next/previous buttons so you are able to place any code which should happen when clicking or key pressing only once.

Jquery capture tab + some key combination

How can I catch, for example, tab+t combination with jQuery? I've found a lot of examples with alt, shift and ctrl, since event object contains special flags in order to understand if, for example, alt was pressed. But there is not such thing for tab.
This should work. It's a bit convoluted and there is likely an easier way, but it works fine.
JSFiddle: https://jsfiddle.net/spybhhxc/
var tabdown = false;
var tdown = false;
$(document).keydown(function(e) {
if(e.which == 9) {
tabdown = true;
}
if(e.which === 84)
{
tdown = true;
}
if(tabdown && tdown)
{
//do your thing
}
});
$(document).keyup(function(e) {
if(e.which == 9) {
tabdown = false;
}
if(e.which === 84)
{
tdown = false;
}
});
This presents a problem though, as once you press tab, the document is unfocused as the tab key navigates to elements in a browser. You would be much better off using something like alt or ctrl which don't interact with the browser.
We can have a tab key pressed [tabPressed] variable which will be set to true on key down and unset the same on its key up event. We will using the tab key pressed[tabPressed] variable to check whether it is in pressed state during the other key press activities. The tab keycode is 9.
jsfiddle link http://jsfiddle.net/e3Lveyj2/
var tabPressed=false;
function handleKeyDown(e) {
var evt = (e==null ? event:e);
if(evt.keyCode == 9){
tabPressed=true;
}
if ((tabPressed) && (evt.keyCode == 84)) {
alert ("You pressed 'Tab+t'")
}
}
function handleKeyUp(e) {
var evt = (e==null ? event:e);
if(evt.keyCode == 9){
tabPressed=false;
}
}
document.onkeydown = handleKeyDown;
document.onkeyup = handleKeyUp;

how to run a code when Left Arrow or Right Arrow Key Is Triggered on the keyboard

How to run a code in javascript when Left Or Right Arrow Keys is Triggered on the keyboard?
I am kinda Newbie to programming.
Can someone please guide me?
function leftpress() {
//do action
}
function rightpress() {
//do action
}
document.onkeydown = function(evt) {
evt = evt || window.event;
switch (evt.keyCode) {
case 39://left arrow
leftpress();
break;
case 37://right arrow
rightpress();
break;
}
};
this is the exact code, try it ..
-you can ask me again if you need help.
You need to attach event handler for tracking the key-board events
document.addEventListener("keydown", keyDownevent, false);
function keyDownevent(e) {
var keyCode = e.keyCode;
if (e.keyCode === 37) {//right
// Your Code
}
else if (e.keyCode === 38) {//UP
// Your Code
}
else if (e.keyCode === 39) {//left
// Your Code
}
else if (e.keyCode === 40) {//DOWN
// Your Code
}
}
Working Example
It's simple with Jquery:
Try this :
$(document).keydown(function (e) {
e.stopImmediatePropagation();
if (e.keyCode === 37) {//right
// Your Code
}
else if (e.keyCode === 38) {//UP
// Your Code
}
else if (e.keyCode === 39) {//left
// Your Code
}
else if (e.keyCode === 40) {//DOWN
// Your Code
}
});
If you are new to Javascript, then may I advise on using libraries to make things easier (because you may end up fixing a lot of cross-browser issues) :)
jQuery is a good one, here are some keyboard events. http://api.jquery.com/category/events/keyboard-events/
First you need to get the value of the key you pressed, with jquery it is done like this:
$(‘#keyval’).keyup(function(e) {
console.log(e.which)
});
Then you do the test to see what value those keys has and then check for keyup event, check if it has than value and then do the action, like this:
$(document).keypress(function(e) {
if(e.which == //arrow value) {
// your action
}
});
I have not tested it but it must work.

Jquery keydown event only working every second press?

Essentially I've created a thumbnail gallery which you can scroll through using the left and right arrows. The right arrow event works perfectly fine, so I assumed that the left arrow event would be the same except with a (-) value. However when I press the left key it only goes to the previous thumbnail every SECOND time.
Can somebody take a look at my code and let me know what I'm missing? Thanks!
$(document).bind("keydown", function(event) {
if (event.keyCode == 39)
{
$("#thumbnail img").each(function(i) {
if ($(this).hasClass("currentThumb"))
{
currentSelectionIndex = i;
$("#thumbnail img").removeClass("currentThumb").addClass("thumb");
if (currentSelectionIndex == 14 && parseInt($('#end').text()) < parseInt($('#total').text()))
{
nextImages(currentCategory.value);
}
}
if(i == currentSelectionIndex + 1)
{
$(this).removeClass("thumb").addClass("currentThumb");
$(this).parent().click();
}
});
}
if (event.keyCode == 37)
{
$("#thumbnail img").each(function(i) {
if ($(this).hasClass("currentThumb"))
{
currentSelectionIndex = i;
$("#thumbnail img").removeClass("currentThumb");
$("#thumbnail img").addClass("thumb");
if (currentSelectionIndex == 0 && parseInt($('#start').text()) > 1)
{
prevImages(currentCategory.value);
}
}
if(i == currentSelectionIndex - 1)
{
$(this).removeClass("thumb").addClass("currentThumb");
$(this).parent().click();
}
});
}
});
Reversing your selection should be enough to make it go in reverse.
$.fn.reverse = [].reverse; // at the top of your code
// in the event handler for left arrow
$("#thumbnail img").reverse().each(function(i) {
don't forget to change back to +
It may works using keyup instead of keydown. I had some issues with it. If it doesn't work use http://jsfiddle.net so that we can easier solve it.

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.

Categories