Are there any alternatives that can be used in a function to scroll a browser to the top of the page? Right now I'm using: $('html, body').animate({scrollTop: '0px'}, 300);
.
Is there maybe something else, or something that is not jQuery?
Are there any alternatives that can be used in a function to scroll a browser to the top of the page? Right now I'm using: $('html, body').animate({scrollTop: '0px'}, 300);
.
Is there maybe something else, or something that is not jQuery?
Below is a pure JavaScript implementation of a scrollTop function. It uses setInterval as an asynchronous while loop that periodically decrements the pageYOffset value, which represents the scrollbar position relative to the top of the page.
To clarify, a while loop would block other scripts on the page from running and would make the scroll to the top appear instant, irregardless of the step value. Whereas, a setInterval with a 50ms iteration would only block the page once every 50ms and would update the scrollbar UI after each individual iteration.
The function takes a single parameter "step", which determines the rate that the scrollbar moves to the top of the screen. The smaller the step, the slower the rate in which the scrollbar moves to the top.
function scrollTop(step) {
var start = window.pageYOffset;
var count = 0;
var intervalRef = setInterval( (function(interval, curOffset) {
return function() {
curOffset -= (interval * step);
console.info("offset = " + curOffset);
window.scrollTo(0, curOffset);
console.info("pageYoffset = " + window.pageYOffset);
count++;
if(count > 150 || curOffset < 0) clearInterval(intervalRef);
}
})(step, start--), 50);
}
// scroll to the top from the middle of the page in about 5 seconds.
scrollTop(5);
// scroll to the top in about 1 second
scrollTop(15);
// scrolls to the top very fast!
scrollTop(35);
The interval is halted when the offset reaches 0, which means the scrollbar has reached the top of the page.
However, the count checker is there to limit the action to just 150 iterations to prevent you from locking up your browser, in case you decide to modify it. Otherwise, you can remove that condition.
Hiya working demo http://jsfiddle.net/jqj9T/5/ or http://jsfiddle.net/jqj9T/5/show/
Is this what you are looking for, checked in IE - 8 as well, this version works.
http://api.jquery.com/animate/
http://api.jquery.com/scrollTop/
Hope this helps,
Please Note I have started with 150 to demo/show how it works you can change it to 0 in your case.
another version using slow: http://jsfiddle.net/jqj9T/7/
Jquery code
if( $('html,body').scrollTop() != 150 ){
$('html,body').animate({scrollTop: $(window).scrollTop() + 150}, 300);
}