Valeriu Mazare
Valeriu Mazare

Reputation: 323

Go to link when pressing keyboard arrows

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.

Upvotes: 2

Views: 3228

Answers (3)

Patrick Evans
Patrick Evans

Reputation: 42736

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>

Upvotes: 5

Manwal
Manwal

Reputation: 23826

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

Upvotes: 1

Brad Faircloth
Brad Faircloth

Reputation: 327

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

Upvotes: 1

Related Questions