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.

Read more