Davide
Davide

Reputation: 1703

How to change page with Javascript for keyboard navigation?

I would like to allow keyboard navigation for a photo gallery website (one page, one photo). What's the Javascript function to do this? I use the code below to manage keyboard events, and I would like to know how to implement a "goToPage()" function. Thanks for your help.

function checkKey(e)
{
  e = e || window.event;

  switch (e.key)
  {
    case "ArrowLeft":
      goToPage("page1.htm");
    break;

    case "ArrowRight":
      goToPage("page3.htm");
    break;
  }
}

document.onkeydown = checkKey;

Upvotes: 0

Views: 1387

Answers (3)

Viktor S.
Viktor S.

Reputation: 12815

You need a document.location:

function checkKeycode(e)
{
  var keycode;

  if (window.event)
    keycode = window.event.keyCode;
  else
    if (e) keycode = e.which;

  switch (keycode)
  {
    case 37:  // left arrow
      document.location = "page1.htm";
    break;

    case 39:  // right arrow
      document.location = "page3.htm";
    break;
  }
}

document.onkeydown = checkKeycode;

Upvotes: 3

Davide
Davide

Reputation: 1703

[2022 Updated Version]

document.location is the function I needed:

function checkKey(e)
{
  e = e || window.event;

  switch (e.key)
  {
    case "ArrowLeft":
      document.location = "page1.htm";
    break;

    case "ArrowRight":
      document.location = "page3.htm";
    break;
  }
}

document.onkeydown = checkKey;

Upvotes: 1

agryson
agryson

Reputation: 297

As long as your pages are neatly named, you could use

document.location = "http://www.myURL"

But you'll need a cycle for your pages. There are many ways of doing this, such as appending a number to a string that you pass:

var count = 0;
var html;
function previous(){
   html = "http://www.page" + count + ".htm"
   document.location = html;
}
function next(){
   var count +=1;
   html = "http://www.page" + count + ".htm"
   document.location = html;
}

or storing the strings in an array etc.

Upvotes: 0

Related Questions