Skip to content

Instantly share code, notes, and snippets.

@travismillerweb
Created March 4, 2014 09:56
Show Gist options
  • Save travismillerweb/9343502 to your computer and use it in GitHub Desktop.
Save travismillerweb/9343502 to your computer and use it in GitHub Desktop.
JS - Snap To Section
/*
JS - Snap To Section
Snaps elements to the section as users scroll
Reference Link: http://stackoverflow.com/questions/6800404/scrollable-panel-snap-to-elements-on-scroll
*/
var snap_timer;
var scroll_from_mouse = true;
function snapList(){
var snapped = false;
var i = 0;
while(!snapped && i < $('.container li').size()){
var itop = $('.container li').eq(i).position().top;
var iheight = $('.container li').eq(i).outerHeight();
if(itop < iheight && itop > 0){
scroll_from_mouse = false;
snapped = true;
var new_scroll_top = 0;
if(iheight - itop > iheight / 2)
new_scroll_top = $('.container').scrollTop() + itop;
else if(i > 1)
new_scroll_top = $('.container').scrollTop() - ($('.container li').eq(i-1).outerHeight() - itop);
else
new_scroll_top = 0;
$('.container').scrollTop(new_scroll_top);
}
i++;
}
};
$(function(){
$('.container').scroll(function(){
clearTimeout(snap_timer);
if(scroll_from_mouse) snap_timer = setTimeout(snapList, 200);
scroll_from_mouse = true;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment