How do I scroll to the top of the page using JavaScript? The scrollbar instantly jumping to the top of the page is desirable too as I\'m not looking to achieve smooth scroll
Simply use this script for scroll to top direct.
<script>
$(document).ready(function(){
$("button").click(function(){
($('body').scrollTop(0));
});
});
</script>
Try this code:
$('html, body').animate({
scrollTop: $("div").offset().top
}, time);
div => Dom Element where you want to move scroll.
time => milliseconds, define the speed of the scroll.
If you don't need the change to animate then you don't need to use any special plugins - I'd just use the native JavaScript window.scrollTo method -- passing in 0,0 will scroll the page to the top left instantly.
window.scrollTo(x-coord, y-coord);
Parameters
$(document).scrollTop(0);
also works.
Really strange: This question is active for five years now and there is still no vanilla JavaScript answer to animate the scrolling… So here you go:
var scrollToTop = window.setInterval(function() {
var pos = window.pageYOffset;
if ( pos > 0 ) {
window.scrollTo( 0, pos - 20 ); // how far to scroll on each step
} else {
window.clearInterval( scrollToTop );
}
}, 16); // how fast to scroll (this equals roughly 60 fps)
If you like, you can wrap this in a function and call that via the onclick
attribute. Check this jsfiddle
Note: This is a very basic solution and maybe not the most performant one. A very elaborated example can be found here: https://github.com/cferdinandi/smooth-scroll
Try this
<script>
$(window).scrollTop(100);
</script>