Scroll to any element using jQuery

12 March 2012, Danny Connell

In today's front-end landscape of responsive, mobile-friendly sites, I'm finding a frequent need to scroll the user (either up or down) to various different elements on the page. This article will show you a simple, lightweight way to do this...

'Back to top' buttons, 'Jump to menu' buttons, 'Jump to widget' links... there are now all sorts of situations where you would want to smoothly scroll the user to a certain element on the page.

There has been a jQuery plugin around for quite a while that can accomplish this, Arial Flesler's ScrollTo.

This is a wonderful plugin that allows you to scroll in all sorts of different ways.

However, if all you want to do is scroll up or down to an element, by using a selector, then you may prefer this lightweight function:

function scrollToElement(selector, time, verticalOffset) {
    time = typeof(time) != 'undefined' ? time : 1000;
    verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
    element = $(selector);
    offset = element.offset();
    offsetTop = offset.top + verticalOffset;
    $('html, body').animate({
        scrollTop: offsetTop
    }, time);
}

Here's how you might use it to scroll to an element with an ID of 'content' when the user clicks a 'Jump to content' button:

$('a.jump-to-content').click(function () {
    scrollToElement('#content');
});

You can also specify the duration of the scroll animation (in miliseconds):

scrollToElement('#content', 500); // scroll the element #content, and take 500ms to get there

And you may also want to specify a vertical offset. The following will scroll the user to 150px above the #content element:

scrollToElement('#content', 500, -150); // scroll to 150px before the element #content, and take 500ms to get there

Show me the god damn demo page already.

8 comments on “Scroll to any element using jQuery

  1. cristopher ca on said:

    where can i download this script?

  2. Safeer Ahmed on said:

    Very nice . I like this scroll to top.

  3. Marek on said:

    Hey!
    Excellent, light, precisely what I needed.
    Big thanks!

  4. just what i needed, danke!

  5. rama ila on said:

    does not work in IE 9

  6. THANK YOU! Exactly what I was looking for this evening!

  7. Gordo on said:

    awesome
    thanks

  8. eddie on said:

    Gracias!

Leave a Reply

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

*

4,863 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>