Reputation: 323
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
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
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";
}
});
Upvotes: 1
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