Snap To Top of Div/Element on Scroll

cqde picture cqde · Jul 27, 2012 · Viewed 10k times · Source

Can anyone recommend a "best" approach for snapping the scrollbar to the top of an element when scrolling down a page?

For example, if my layout was as follows:

<div id="section-one" style="width: 100%; height: 600px;">
    Section One
</div>

<div id="section-two" style="width: 100%; height: 600px;">
    Section Two
</div>

<div id="section-three" style="width: 100%; height: 600px;">
    Section Three
</div>

<div id="section-four" style="width: 100%; height: 600px;">
    Section Four
</div>

If the user was viewing section one and began browsing down with section two beginning to take part of the browser viewport, I'd like the browser to automatically snap to the top of the next div.

I'm familiar with .scroll() and .scrollTop but a little unsure with where to go from here.

Answer

Okan Kocyigit picture Okan Kocyigit · Jul 27, 2012

you can check if element is in wiewport with this isScrolledIntoView function created by @Scott Dowding,

And here is an example,

$(document).scroll(function() {
    $("div:not(.highlight)").each(function() {
        if (isScrolledIntoView(this)) {
           $("div").removeClass("highlight");
           $(this).addClass("highlight");
           $("body").animate({ scrollTop: $(this).offset().top }, 1000)
        }
    });
});

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return (elemTop <= docViewBottom) && (elemTop > docViewTop);
}​

DEMO