How can I map a key press to hyperlinks in my HTML document using JavaScript? If I press 'a' it should go to www.page.com/a and if I press 'b' it should go to www.page.com/b?

John Zukowski

You need to tell the document what method to call on key presses. The following demonstrates this by uses 'f' to go to the jGuru FAQs pages and 'j' for Jobs.

<SCRIPT LANGUAGE="JavaScript">
  var hotKeys = new Array("f","j");
  var urls = new Array("http://www.jguru.com/faq",
    "http://www.jguru.com/jguru/jobs/search.jsp");

  if( hotKeys.length != urls.length )
    alert("Bad key/URL lists");

  if (document.layers)
    document.captureEvents(Event.KEYPRESS)

  function navigate(e) {
    var enteredKey;
    var arrayKey;

    if (document.layers)
      enteredKey = String.fromCharCode(e.which);
    else if (document.all)
      enteredKey = String.fromCharCode(event.keyCode);

    enteredKey = enteredKey.toLowerCase()

    for(i = 0, n = hotKeys.length; i < n; i++) {
      arrayKey = hotKeys[i].toLowerCase();
      if (arrayKey == enteredKey) {
        window.location=urls[i];
        return(true);
      }
    }
    return(true);
  }
  document.onkeypress=navigate;
</SCRIPT>

F for FAQs and J for Jobs
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact