Skip to content

Scroll To

Use this class to allow elements to trigger a smooth scroll to an element.

Installation

This class is pre-installed and loaded asynchronously with Genesis out of the box.

Import the ScrollTo extension class in your JavaScript file.

import ScrollTo from 'extensions/scroll-to';

Example Usage

.mvt

<!-- Uses Default Initialization... -->
<button type="button" class="js-scroll-to" data-scroll-to="#product-tabs">View Product Details</button>

<!-- Uses Custom Initialization... -->
<button type="button" class="js-scroll-to-write-review">Write Review</button>

.js

Preferred asynchronous initialization:

(async () => {
    const triggerElements = document.getElementsByClassName('js-scroll-to');

    if (!triggerElements.length) {
        return;
    }

    const {default: ScrollTo} = await import('extensions/scroll-to');

    new ScrollTo(triggerElements, {
        scrollIntoViewOptions: {
            behavior: 'smooth',
            block: 'end',
            inline: 'nearest'
        }
    });
})();

Alternatively:

import ScrollTo from 'extensions/scroll-to';

new ScrollTo(document.getElementsByClassName('js-scroll-to'), {
    scrollIntoViewOptions: {
        behavior: 'smooth',
        block: 'end',
        inline: 'nearest'
    }
});

Options

The ScrollTo class can take an optional object as the second parameter to override any of the default configuration options.

The following table defines the available configuration options:

Name Type Description Default Value
beforeScroll Function Null This function will be called before scrolling so that JS methods can be used to hook into the click-event of the triggers, modify the dom (ex show a hidden target DOM element), and then scroll to the scrollTo element. null
scrollToAttribute String The scroll to data attribute on the trigger elements. Used when the scrollToSelector option value is not provided or empty. 'data-scroll-to'
scrollToSelector String Selector to explicitly target the scroll to element. ''
scrollIntoViewOptions Object Object to be passed into the Element.scrollIntoView() function when the scroll-to is performed. {}