Snap to top of Div / Element on scroll

Can anyone recommend a β€œbetter” approach for tying a scrollbar to the top of an element when scrolling 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 a user browsed the first section and started browsing down, and the second section began to take part in the browser viewing window, I would like the browser to automatically snap to the top of the next div.

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

+4
source share
3 answers

you can check if an item is in wiewport using 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

+8
source

What you can do is install

 body { overflow:hidden } 

and have control over user interactions, let's say you have a menu if the user selects a section from a menu that you just animate with scrollTop to redirect to the section.

Another solution, since you have a specific height that is 600px, you can calculate with scrollTop and scroll where the user is in the document, something like this ...

 $(window).scroll(function () { console.log($(window).scrollTop()); });​ 

Example: http://jsfiddle.net/3STQN/

0
source

If several divs can enter a view, then you can change the isScrolledIntoView function to, say, isTopInTheView, or something similar. In this function, you can check if the top of the div is visible, and if so, bind that div to the top of the screen.

EDIT: and, of course, as soon as you find the first div that satisfies the requirements, just return from the function so that it cannot check more divs.

0
source

All Articles