JS Scroll To

Overview

The js-scroll-to module is used to achieve smooth scrolling to a particular element on a page. Specifically, when an element with the class js-scroll-to is clicked, the page will smoothly scroll until the top of the target element is aligned with the top of the visible scroll area, plus or minus a fixed pixel offset, if specified.

One day, we may be able to achieve this with pure CSS. But we're still waiting on better browser support, so for now we must use JavaScript.

The Visible Scroll Area

Because it is quite common for certain elements (e.g. a "sticky" site header) to be pinned to the top of the screen, we must calculate the true visible scroll area of the screen, i.e. the vertical area that is not obscured by pinned elements. The js-scroll-to module requires that all elements pinned to the top of the screen are given the class js-is-fixed-top in order for the global scroll calculation to work correctly.

Settings

data-scroll-to-target

This mandatory attribute represents the jQuery selector for the element that the page should scroll to. Generally an id, e.g #section-1

data-scroll-to-speed

This attribute represents the duration, in milliseconds, that the scroll animation should last. Default is 500.

data-scroll-to-offset

This attribute represents the pixel offset that should be used when scrolling to the target element. Use a positive number to stop before hitting the top of the target element, and a negative number to go past the top of the target element. Default is 0.

Examples

Basic

Welcome to #section-1

Custom Scroll Speed

Welcome to #section-2. It should have taken you a little longer to get here.

Custom Scroll Offset

Welcome to #section-3. You should notice a 30px offset above me.