2

I have 2 links: <a href='leftLink.php'><< Prev</a> and <a href='rightLink.php'>Next >></a>.

Can it be possible to go to leftLink when pressing left arrow from keyboard, and to rightLink.php when pressing right arrow from keyboard? Any advice would be very welcome

Thank you in advance.

Valeriu Mazare
  • 323
  • 5
  • 12
  • Worth considering that this approach might hijack arrow keys for screen readers that use them to navigate through various page elements: https://webaim.org/techniques/keyboard/ – Dave Everitt May 10 '23 at 20:23

3 Answers3

5

You can setup a keyboard event listener (keydown or keyup) on the document.

document.addEventListener('keydown',(event)=>{});

Check the key property (modern browsers) or keyCode (deprecated, older browsers) on the event object for the appropriate value corresponding to the left and right arrows.

switch(event.key){
    case 'ArrowLeft':
    break;
    case 'ArrowRight':
    break;
}

Then use the click() method of the respective link to trigger the navigation.

document.getElementById("prevLink").click();

let prevLink = document.getElementById("prevLink");
let nextLink = document.getElementById("nextLink");
document.addEventListener("keydown", ({key}) => {
  switch (key) {
    case 'ArrowLeft':
      console.log('Left arrow');
      prevLink.click();
      break;
    case 'ArrowRight':
      console.log('Right arrow');
      nextLink.click();
      break;
  }
});
<a id="prevLink" href='#prevUrl'><< Prev</a>

<a id="nextLink" href='#nextUrl'>Next >></a>
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
1

Use this to detect keypress..

function checkKey(e) {
    var event = window.event ? window.event : e;
    if (true) {
        alert(event.keyCode)
    }
}

from here determine the key pressed and use document.location to redirect the browser.

keycodes are:

left = 37
up = 38
right = 39
down = 40
Brad Faircloth
  • 337
  • 1
  • 7
1

You can try this:

$("body").keydown(function(e) {
  if(e.keyCode == 37) { // left
    //your code
    window.location.href = "leftLink.php";
  }
  else if(e.keyCode == 39) { // right
    //your code
    window.location.href = "rightLink.php";
  }
});

Reference

Community
  • 1
  • 1
Manwal
  • 23,450
  • 12
  • 63
  • 93
  • 1
    jQuery is not tagged, you should show a pure javascript solution, and then suggest jQuery if needed. While jQuery is a good library, he might not be using it, and adding it just for this would just add overhead to do a simple task – Patrick Evans Apr 06 '14 at 17:41
  • OP did't mention he want javascript solution. @PatrickEvans +1 for your ans this one is also good. – Manwal Apr 06 '14 at 17:44
  • OP has it tagged javascript, I am just saying since it is not tagged with jQuery you cannot assume he knows what jQuery is or know if he is even using it. – Patrick Evans Apr 06 '14 at 17:49