Question

I have infinite scrolling implemented in a page. I need to provide a button or a simple link which when clicked lets the user scroll to the top of the page.

How can I implement it using jQuery or plain JavaScript?

2 Answers

If you want smooth scrolling i.e. the users should not notice the jump all at once, but instead over a small period of milliseconds, you can use the animate effect in jQuery as follows:

<script>
  $("a[href='#top']").click(function() {
    $("html, body").animate({ scrollTop: 0 }, "fast");
    return false;
  });
</script>

This will take any 'a' tag whose href="#top" and make it scroll to the top smoothly. Note that the scrollTop is a property of the window element.


If you are OK with the scroll bar instantly jumping to the top left i.e. if you don't need to animate smooth scrolling then you don't need to use the jQuery and can just use the native JavaScript window.scrollTo method and pass 0 (pixel along the horizontal axis) and 0 (pixel along the vertical axis) values to it.

window.scrollTo(0, 0);