I have a page with prev and next links:
<link rel="prev" href=";#63;referer=index.php">
<link rel="next" href=";#63;referer=index.php">
Is it possible to use Javascript to navigate these links if the user presses Left arrow or Right arrow? The link should not activate if they are editing text and the Left or Right arrow is pressed.
This will be used to simplify viewing several image pages.
I have a page with prev and next links:
<link rel="prev" href="http://camera.phor/cameralife/photos/11096?referer=index.php">
<link rel="next" href="http://camera.phor/cameralife/photos/5679?referer=index.php">
Is it possible to use Javascript to navigate these links if the user presses Left arrow or Right arrow? The link should not activate if they are editing text and the Left or Right arrow is pressed.
This will be used to simplify viewing several image pages.
Share Improve this question asked Sep 4, 2011 at 19:59 William EntrikenWilliam Entriken 39.5k23 gold badges158 silver badges211 bronze badges 1- A word of accessibility caution: this can hijack arrow keys as screen readers use them to navigate through page elements: webaim/techniques/keyboard – Dave Everitt Commented May 10, 2023 at 20:25
2 Answers
Reset to default 4Without jQuery: http://jsfiddle/UXPLt/1/.
document.onkeyup = function(e) { // key pressed
if(document.activeElement.nodeName === "INPUT"
|| document.activeElement.nodeName === "TEXTAREA") {
return; // abort if focusing input box
}
var elems = document.getElementsByTagName("link"),
links = {};
for(var i = 0; i < elems.length; i++) { // filter link elements
var elem = elems[i];
if(elem.rel === "prev") { // add prev to links object
links.prev = elem;
} else if(elem.rel === "next") { // ad next to links object
links.next = elem;
}
}
if(e.keyCode === 37) { // left key
location.href = links.prev.href;
} else if(e.keyCode === 39) { // right key
location.href = links.next.href;
}
};
$(document).keydown(function(e){
if (e.keyCode == 37) { // left
$( "a[rel='prev']" ).click();
return false;
} else if (e.keyCode == 39) { // right
$( "a[rel='next']" ).click();
return false;
}
});