Scroll to the top of the page using JavaScript? – Dev

The best answers to the question “Scroll to the top of the page using JavaScript?” in the category Dev.

QUESTION:

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 scrolling.

ANSWER:

If you do want smooth scrolling, try something like this:

$("a[href="#top"]").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
  return false;
});

That will take any <a> tag whose href="#top" and make it smooth scroll to the top.

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(xCoord, yCoord);

Parameters

  • xCoord is the pixel along the horizontal axis.
  • yCoord is the pixel along the vertical axis.

ANSWER:

Try this to scroll on top

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

ANSWER:

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