Skip to content Skip to sidebar Skip to footer

How Can One Smooth Scroll Up And Down Between Objects On A Page With Arrow Keys?

I am building a very simple website with a series of images arranged vertically on a page. I would like to be able to use the up and down arrow keys to smooth scroll from one image

Solution 1:

This is a fun and easy one if you know jQuery. Catch the up/down arrow key presses and prevent their default scroll action. Then find the next or previous image based on the arrow press. Finally use jQuery's animate to bring the top of the element into view. You'll need to put in some error checking for when you go past the end of the list, but I am sure you can figure it out based on this.

http://jsfiddle.net/aVvQF/4/

$(window).keydown(function(e) {
    e.preventDefault(); //prevent default arrow key behaviorvar targetElement;
    //downif (e.keyCode == 40) {
        $targetElement = $('.active').next('img');
    }
    //upelseif (e.keyCode == 38) {
        $targetElement = $('.active').prev('img');
    }
    if (!$targetElement.length) {return;}
    $('.active').removeClass('active');
    $targetElement.addClass('active');

    //scroll element into view    
    $('html, body').clearQueue().animate({scrollTop: $targetElement.offset().top }, 1000);
});

Post a Comment for "How Can One Smooth Scroll Up And Down Between Objects On A Page With Arrow Keys?"