简体   繁体   中英

Keyboard shortcut to navigate a website

I'm building a PHP application framework where all pages are created dynamically such as:

  • domain.com/1/
  • domain.com/2/
  • domain.com/3/
  • etc...

Now I want to add a support so that users can simply use their keyboard to navigate through the site. (May be pressing and keyboard keys)

Is that something doable? If so, what do I need to use?

You would definitely need to use JavaScript to capture all of the keydown (note, arrow keys will not fire keypress event) events. For instance, Ctrl + 2 would go to the /2 page, Ctrl + 3 would go to the /3 page.

I think you'd need a way to map the keypress events to the actual page names. I'd suggest maintaining a layer of abstraction, such as a mapping file, between keydown event codes and the actual page names so that the keycodes could be customized in the future if needed.

Do a search on this event to get you started. The example below captures the enter key

   if(event.keyCode == 13) {
       // do stuff
   }

Here is the list of keycodes: http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx

To create events for these keys, I would suggest starting out by creating events for them. You will need jQuery for this example, although there are ways to accomplish the same in pure JavaScript:

// bind keydown events to the window
$(document).keydown(function(event) {
    if (event.which == 37) {  
       // left arrow - run your code to change back a page
       alert('left');
    } else if(event.which == '39') {
       // right arrow - run code to move forward a page
       alert('right');
    }
 });

Table of key events by browser and keys: http://www.quirksmode.org/js/keys.html

List of key codes: http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM