Advertisement
Advertisement


Scroll to the top of the page using JavaScript?


Question

How do I scroll to the top of the page using a JavaScript? It is desirable even if the scrollbar instantly jumps to the top. I'm not looking for a smooth scrolling.

2019/10/28
1
1629
10/28/2019 1:01:24 PM

Accepted Answer

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

  • x-coord is the pixel along the horizontal axis.
  • y-coord is the pixel along the vertical axis.
2014/06/27
2215
6/27/2014 3:10:52 PM


Try this to scroll on top

<script>
 $(document).ready(function(){
    $(window).scrollTop(0);
});
</script>
2017/03/01

Better solution with smooth animation:

// this changes the scrolling behavior to "smooth"
window.scrollTo({ top: 0, behavior: 'smooth' });

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo#Example

2018/10/23

You don't need jQuery to do this. A standard HTML tag will suffice...

<div id="jump_to_me">
    blah blah blah
</div>

<a target="#jump_to_me">Click Here To Destroy The World!</a>
2009/07/17

All of these suggestions work great for various situations. For those who find this page through a search, one can also give this a try. JQuery, no plug-in, scroll to element.

$('html, body').animate({
    scrollTop: $("#elementID").offset().top
}, 2000);
2012/04/23

smooth scroll, pure javascript:

(function smoothscroll(){
    var currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
    if (currentScroll > 0) {
         window.requestAnimationFrame(smoothscroll);
         window.scrollTo (0,currentScroll - (currentScroll/5));
    }
})();
2015/05/29

Source: https://stackoverflow.com/questions/1144805
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]