Thursday, January 12, 2012

Simulate top scroll using javacsript setInterval & clearInterval


I want to simulate scroll by moving body/html frame to the top/upwards by arbitrary amount. I know jQuery scroll or animate function, .scroll() and .animate() . But I have decided not to use it since it caused conflict between scrollTop property in animate and .scroll() jQuery native function when the animation happens and is still ongoing AND the .scroll gets called..



My plan is now to just simulate scroll by moving body/html frame to the top as smooth as possible by some arbitrary amount, and then STOP (clear the interval) when there's a native scroll happens ( .scroll() gets invoked).



I am able to stop the setInterval animation when .scroll() is called, but I am still not able to move the html object to the top by the amount I want it to "scroll" (which means my code only partially works).



Here is what I have so far:




var scrollTop = //Some arbitrary value
var fakeScroll = setInterval(function(){
console.log(scrollTop);
var animObj = $('html,body');
animObj.top = animObj.offset().top + scrollTop;
},500);
$(document).scroll(function(){
clearInterval(fakeScroll);
});



Appreciate any suggestions/answers. Thanks!

No comments:

Post a Comment