I am trying to build a site with keyboard navigation. I want the user to be able to navigate through a menu of five or six pages using the left and right arrows. No matter on which page is the user, I want him/her to go back/forward in the menu when the left/right arrow is pressed.
Let's say the horizontal menu is built this way :
[Home / Random page / Some page / Another page / And so on]
Apparently it is not working. Here is what I have so far :
document.onkeyup = KeyCheck;
var pages = ["index.php", "random-page.php", "some-page.php", "another-page.php", "and-so-on.php"];
function leftarrowpressed() {
location.href = pages[0]-1;
}
function rightarrowpressed() {
location.href = pages[0]+1;
}
}
function KeyCheck(e)
{
var KeyID = (window.event) ? event.keyCode : e.keyCode;
switch(KeyID)
{
// left arrow key
case 37:
leftarrowpressed()
break;
// right arrow key
case 39:
rightarrowpressed()
break;
}
}
Thank you all for your help.
Well, seems to me you'll need to know which page you're currently on each time for it to work. For this I'd recommend window.localStorage if (and only if) A) all of the pages are served from the same domain, and B) You don't need to support older browsers. If either of those are untrue, this method won't work, and you'll need to do something else like parse the URL string.
I took your code and modified it slightly to show how you might use localStorage. I added some comments, but it should be relatively self-explanatory. Here 'tis:
But - I've gotta ask - do you really want to do it this way? that's a lot of HTTP requests and refreshing the page - are the pages small enough that you could just load them all together at once, and simply only display one at a time? (you could even do a cool sliding or crazy 3d effect between pages - again, assuming you only need to support newer browsers...)
okay, I checked out your site and modified/extended my code slightly to try to (almost) achieve what it is I think you want to do. I'm going to leave the other answer unedited because it shows what is probably a better method for doing this... This solution is rather hack-y, and just a way to illustrate the concept.
To see it, go to any of your pages (except the blog page), then open up webkit inspector (my code will only work in WebKit(chrome/safari), although it would be REALLY easy to make it work in any browser) and enter the following into the javascript console:
Keep in mind, though, this is a really hack-y way to do it, but it should point you in the right direction. Let me know if you have more questions.
pages[0]-1
will evaluate to"index.php"-1
which isNaN
. You don't want to subtract 1 from the page URL (you basically cannot subtract from strings) - rather subtract1
from the index to get the previous page. Also, guard for the bounds:and:
I guess you replace the
0
with the index of the current page automatically.Secondly, you have an extraneous
}
inrightarrowpressed
it seems.