2

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.

Edvard
  • 475
  • 4
  • 8
  • 17

2 Answers2

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