jquery tip

A common request when working on a web site or application, is to have some kind of “auto-scroll” effect. In other words, I’m talking about that thing where you click a button or navigation item, and the page takes a few hundred milliseconds to gently scroll up/down to an element.

Perhaps you want to highlight your CTA (eg. Call to Action), etc.

Let’s take care of this with a trivial amount of jQuery!

Option A: Add some small jQuery

Once jQuery is included / loaded on the page, we can tap into the animate() method to create some nice smooth scrolling.

Let’s look at the following:

  $(function() {
     $('.scroll').on('click', function(e) {
        var offset = $(this).data('offset') || 0;
        var target = this.hash;
        $('html, body').stop().animate({
            'scrollTop': $(target).offset().top - offset
        }, 500);

I’ve added an offset parameter here, to allow you to specify via a data- attribute an offset to your target element. This can be handy if you want to scroll up/down to a target element, but stop a small bit of distance before it.

With this snippet in place, now we can enhance a navigation element.

Let’s look at a basic use of our new click handler:

<a class="scroll" href="#targetElement">Scroll to Target</a>

So at this point, some simple scroll handling is in place. Clicking on that link will cause the page the scroll to whatever target element you specify.

Now let’s add an offset. Sometimes when you tinker with page scrolling this way, it can create a bit of “weirdness” depending on your existing CSS. The page scrolls properly, but maybe the way your target element is positioned, the page is just a touch too high or low. This is where the offset helps us out.

Let’s update our snippet to specify that offset:

<a class="scroll" href="#targetElement" data-offset="200">Scroll to Target</a>

Now in this example, if you click the link, the page will scroll to a point 200 pixels above the target element.

Option B: Use the jQuery.scrollTo Plugin

A properly written jQuery Plugin will usually “play nice” with any existing JavaScript on the page, so another option is to grab the jQuery.scrollTo plugin.

Hope you enjoyed this tip, please like and share it!