I'm trying to find the simplest code, whether it's standalone or with jQuery, that does this: when I press j on my keyboard, I'm redirected to the next div below and when I press k, I'm sent back to the div above. Extra points if it can scroll smoothly.
Asked
Active
Viewed 1,107 times
2
-
2You cant give extra points so dont lie to me!!! – Loktar Sep 01 '11 at 18:59
-
1Possible duplicate of http://stackoverflow.com/questions/2168739/using-arrow-keys-with-jquery-scrollto – CashIsClay Sep 01 '11 at 19:00
-
I meant extra points figuratively, haha. Artsemis, I hadn't seen that question and I did search before I posted but sorry anyway. – Edvard Sep 01 '11 at 19:58
2 Answers
1
I think you'll want to use a combination of the following two plugins:
http://plugins.jquery.com/project/hotkeys
and
http://plugins.jquery.com/project/ScrollTo
which you could use in this kind of fashion:
$(document).bind('keydown', 'j', whenyoupressj);
$(document).bind('keydown', 'j', whenyoupressk);
and the actually scrolling part could be:
$.scrollTo( '#someid', 800, {easing:'elasout'} );

Joseph
- 25,330
- 8
- 76
- 125
0
I would do this with jQuery in a way like this:
$(document).keydown(function (e) {
// Handle only [J] and [K]...
if (e.keyCode < 74 || e.keyCode > 75) {
return false;
}
// Find the "active" container.
var active = $('div.active').removeClass('active');
var newActive;
// Handle [J] event.
if (e.keyCode == 74) {
newActive = active.next('div');
//if (newActive.index() == -1) {
// newActive = $('div', container).last();
//}
}
// Handle [K] event.
else if (e.keyCode == 75) {
newActive = active.prev('div');
//if (newActive.index() == -1) {
// newActive = $('div', container).first();
//}
}
if (newActive !== undefined) {
newActive.addClass('active');
$(document).scrollTop(newActive.position().top);
}
});

philipproplesch
- 2,127
- 17
- 20