Scroll to position with jQuery

If you need to scroll to a specific location on the page this little custom jQuery function can help you out. This snippet will help you scroll to a particular section based on the element you choose.

Add this little snippet inside your scripts file.


$.fn.scrollView = function () {
  return this.each(function () {
    $('html, body').animate({
      scrollTop: $(this).offset().top
    }, 1000);
  });
}

Add this (also in your scripts file) and modify it to be the element which you would like to scroll to.


 $('#your-element').scrollView();

This snippet calculates #your-elements‘s position and scrolls your browser window to it. The duration is set at 1 second.

You could use the above snippet it many ways. A very simple example would be to trigger the function inside a click event.


$('#your-link').click(function (event) {
  event.preventDefault();
  $('#your-div').scrollView();
});

Feel free to explore the demo or download the code.

3 Comments

  1. It would be nice if there was a demo of this to see how it works.

    • Hey Dan!

      Thanks for the idea!

      Here is a demo.

      If you are not familiar with GitHub, just download it via the ‘zip cloud icon’ and have a play around. When I get time I will try and clean it up.

      Hope that helps.

  2. Thanks man it works for me excellent :)

This post currently has 3 responses. What do you think?

You can use basic HTML when posting code, please turn all < characters into &lt; or > into &gt;
If the code is multi-line, use <pre><code></code></pre>

Leave a Reply

Your email address will not be published. Required fields are marked *