Animated scroll to an element using jQuery

As more sites go responsive and ‘one pager’, it’s often you see a smooth animated scroll effect when you click a link or element on a site. It just looks nicer than an anchor, which promptly jumps you down/up the page…eughh.Using just a few lines of jQuery can achieve this nice effect. Here’s how it goes.

Firstly, we create a function to handle this effect:

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

This gives us the ability to pass three parameters:

  • The element that we would like to scroll to, e.g. #content.
  • The transition time for the scroll which we can pass in milliseconds, e.g. 2000 (2 seconds).
  • A vertical offset, which can be handy in various ways. An example is if your header sticks to the top of the page at all times, you could minus the height of this from the vertical offset. This would mean when the user scrolls to the element, your header does not cover it.

Finally, we just trigger the above function…also using jQuery.

Lets say you have an image which, when clicked, you would like to scroll the user to an area of content:

<img src="path/to/image" class="myimage" alt="My image" />

You can use the jQuery .bind() method to attach a click event to the image, which then calls the function:

 $('.myimage').bind("click", function() {
    scrollToElement('#content', 1000, -50);

And there you are, all done.