How do you create arrow keys navigation for a Tumblr theme using JavaScript?
I'm trying to write some JavaScript to allow users of a Tumblr theme to use the left
and right
arrow keys to navigate pages.
I've managed to get the basic concept working:
document.onkeydown = function(event) {
event = event || window.event;
var key = event.keyCode;
var currentPage = {CurrentPage};
// left arrow key
if (key == 37) {
var previousPage = currentPage - 1;
window.location.href = "/page/" + previousPage;
}
// right arrow key
if (key == 39) {
var nextPage = currentPage + 1;
window.location.href = "/page/" + nextPage;
}
};
This runs into the problem of users being able to go beyond the last page and might (I'm not exactly sure) work on permalink pages. However, it would be much easier to use the {PreviousPage}
and {NextPage}
variables for the URLs, but I can't get them to work in JavaScript for some reason. Even if I prefix them with JS (ie {JSPreviousPage}
and {JSNextPage}
) they still resolve to nothing, despite the variables working fine in HTML.
Add next and prev IDs to your pagination anchors links. Then try this:
$(document).keydown(function(e) {
var url = false;
// Left arrow key code
if (e.which == 37) {
url = $('#prev').attr('href');
}
// Right arrow key code
else if (e.which == 39) {
url = $('#next').attr('href');
}
if (url) {
window.location = url;
}
});
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.