makeee
makeee

Reputation: 2805

Scrolling down to the next element with javascript

I'm implementing keyboard controls on my website that allow the user to move down to the next div (that has the class "post"), as well as up to the previous div, with the keyboard arrow keys.

I can bind a function to the keypress just fine, I just need some help with the javascript (i'm using jquery) that determines which div is the next / previous.

It's important that if the user scrolls halfway down the screen with the standard scrollbar, the next item is whatever is next, relative to the top of their viewing window, so I know I need to calculate the next/previous divs using the users current scroll position.. but I'm a bit lost on how to do that.

Upvotes: 0

Views: 1364

Answers (1)

Nick Jurista
Nick Jurista

Reputation: 1434

Firstly, you're going to have to test for the current scrollbar position with $(document).scrollTop().

Once you have that, you can iterate over your elements using $(".post").each(), comparing their top offset to the scrollbar position. If it's lower than the scrollbar, that is your next element, so break out of the loop with return false.

Full example:

var scrollPosition = $(document).scrollTop(),
    nextPost = 0,
    currentPosition = 0;
$(".post").each(function() {
    currentPosition = $(this).offset().top;
    if (currentPosition > scrollPosition) {
        nextPost = currentPosition;
        return false; // break the loop
    }
});
$(document).scrollTop(nextPost); // Scrolls the page to the post

Upvotes: 1

Related Questions