Reputation: 5150
Is there a simple way to force the browser to scroll to the top if a button is clicked?
I have tried
jQuery('html').scrollTop();
jQuery('body').scrollTop();
jQuery(window).scrollTop();
None of them seem to scroll to the top of the page.
Upvotes: 24
Views: 62663
Reputation: 1496
Since nobody mentioned the required HTML I'll add it here.
First create your anchor element:
<a href="#" title="Scroll to Top" class="ScrollTop">Scroll To Top</a>
Note the class is referenced by the following jQuery.
Then add your jQuery:
$(document).ready(function(){
$('.ScrollTop').click(function() {
$('html, body').animate({scrollTop: 0}, 800);
return false;
});
});
To adjust the speed of the animation change the "800" value.
Upvotes: 2
Reputation: 30015
Due to cross browser oddness, some browsers will respond to 'html'
and some to 'body'
. And maybe its just my luck, but .scrollTop(0)
has never worked for me to move the page. Give this a shot:
jQuery('html,body').animate({scrollTop:0},0);
This version is tested and cross browser for all desktop browsers, and mobile devices.
Upvotes: 55
Reputation: 29025
This is the cross browser way,
function scrollableElement(els) {
for (var i = 0, argLength = arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}
var scrollElem = scrollableElement('html', 'body');
$(scrollElem).scrollTop(0);
Code from css-tricks
Upvotes: 0
Reputation: 145458
You can use either this:
jQuery('body').scrollTop(0);
or this:
jQuery(window).scrollTop(0);
or finally this:
jQuery('html').scrollTop(0);
So, in order to call the scrollTop
method and make your page scrolling you should pass an argument with the numeric value representing the scrollTop position. Otherwise it will work as if you need to get the scrollTop position.
Two last methods should work constantly in all browsers, while the first might not work in some versions of IE.
Upvotes: 6