Reputation: 1107
I'd like the user to be able to load the next or previous page when they press left or right on the keyboard. The next and previous links for each page are contained within two buttons.
The html...
<a href="/page-link-prev" class="prev button">< Prev</a>
<a href="/page-link-next" class="next button">Next ></a>
Some jquery I found that registers the right key presses, but doesn't change the url obviously, it just shows an alert.
$(function() {
$(document).keyup(function(e) {
switch(e.keyCode) {
case 37 : alert('You pressed Left'); break;
case 39 : alert('You pressed Right'); break;
}
});
});
Upvotes: 0
Views: 2889
Reputation: 57685
You can use .load()
to load from a URL to a portion of the page.
.load( url, [data,] [complete(responseText, textStatus, XMLHttpRequest)] )
Load data from the server and place the returned HTML into the matched element.
I'm assuming you have a specific div
you want to refresh w page contents, and you don't want to refresh the entire page
$(function() {
$(document).keyup(function(e) {
switch(e.keyCode) {
case 37 : $('#page').load($(".prev").attr("href")); break;
case 39 : $('#page').load($(".next").attr("href")); break;
}
});
});
Or, if you want to refresh the entire page you can use window.location
Whenever a property of the location object is modified, a document will be loaded using the URL as if window.location.assign() had been called with the modified URL.
$(function() {
$(document).keyup(function(e) {
switch(e.keyCode) {
case 37 : window.location = $('.prev').attr('href'); break;
case 39 : window.location = $('.next').attr('href'); break;
}
});
});
You can replace #page
with the element you are refreshing.
Upvotes: 3
Reputation: 989
I think you have to use the location property of the window object like this:
$(function() {
$(document).keyup(function(e) {
switch(e.keyCode) {
case 37 :
window.location="/page-link-prev";
break;
case 37 :
window.location="/page-link-next";
break;
}
});
});
Or you can trigger the click event on the jQuery object of your anchor.
Upvotes: 1