Search code examples
javascriptnavigationkeyboard

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;

Solution

  • [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;