How can I "snap" scroll to the nearest predefined position?
javascript, jquery, scroll
Solution
There is a CSS spec for this, and it is well supported with native rendering and very nice touch behavior except on Chrome: http://caniuse.com/#feat=css-snappoints
For the laggard browser, there's a polypill: https://github.com/ckrack/scrollsnap-polyfill
See also How to emulate CSS Scroll Snap Points in Chrome?
Problem
I have a website that is essentially four divs - each of which is set to the height of the window so that the total document is four times the height of the window. The idea is that a click on a div advances the scroll by one "window height" - which works fine, like this: ``` // on click event if(cur_frame<number_slides){ scrolling = true; $('html,body').animate({scrollTop:window_height*cur_frame},function(){ scrolling=false; }); } ``` After the user scrolls the page manually, however, I'd like to "snap" the position to the nearest multiple of the window height - so a given div is once again centered on the screen. I tried using a timeout, figuring that a small delay would keep it from triggering a thousand times a second... ``` // on scroll event clearTimeout(scroll_timer); if(!scrolling) scroll_timer = setTimeout(function(){ if(cur_scroll!=window_height*(cur_frame-1)) { scrolling = true; $('html,body').stop().animate({scrollTop:window_height*(cur_frame-1)},function(){ scrolling = false; }); } },100); //20? 400? 1000? ``` ...but couldn't strike a balance between the script fighting the user over scroll position, or a seriously long delay that defeats the "snapping" effect. Any suggestions how this might be achieved?