@three11/animate-top-offset

Scroll a container to a specific Y offset

Usage no npm install needed!

<script type="module">
  import three11AnimateTopOffset from 'https://cdn.skypack.dev/@three11/animate-top-offset';
</script>

README

GitHub release GitHub issues GitHub last commit Github file size Build Status npm npm Analytics

Animate Top Offset

Vanilla JS animated scroll to a given offset.

Install

npm i @three11/animate-top-offset

or

yarn add @three11/animate-top-offset

or

Just download this repository and link the files located in dist folder:

<script src="path-to-animate-top-offset/dist/animate-top-offset.min.js"></script>

or

Include it from Unpkg CDN

<script src="//unpkg.com/@three11/animate-top-offset/dist/animate-top-offset.min.js"></script>

Usage

First, import the module:

import animateTopOffset from '@three11/animate-top-offset';

Then use the module:

With one element

const button = document.getElementById('button');

button.addEventListener('click', event => {
    event.preventDefault();

    const href = event.target.getAttribute('href');
    const offset = doc.querySelector(href).offsetTop;

    animateTopOffset(offset);
});

With many elements

const buttons = document.querySelectorAll('.js-scroll-to');

// Instead of Array.from you can spread the buttons: [...buttons]
Array.from(buttons).forEach(button => {
    button.addEventListener('click', event => {
        event.preventDefault();

        const href = event.target.getAttribute('href');
        const offset = doc.querySelector(href).offsetTop;

        animateTopOffset(offset);
    });
});

The examples above assume that you have a modern ES6 setup installed and configured (Webpack, Babel, etc). If not you can always fallback to ES5:

const buttons = document.querySelectorAll('.js-scroll-to');

[].forEach.call(buttons, function (button) {
    button.addEventListener('click', function (event) {
        event.preventDefault();

        var href = event.target.getAttribute('href');
        var offset = doc.querySelector(href).offsetTop;

        animateTopOffset(offset);
    });
});

Arguments

The function accepts four arguments:

  • offset
  • container
  • speed
  • easing
animateTopOffset(0, window, 2000, 'easeOutSine');

Default values are:

  • offset = 0
  • container = window
  • speed = 2000
  • easing = 'easeOutSine'

Calling the function with the default values (animateTopOffset()) will scroll the window back to top.

There are three built-in easing functions:

  • 'easeOutSine'
  • 'easeInOutSine'
  • 'easeInOutQuint'

Demo

A minimal demo is available here Clicking on the links in the menu scrolls the page to the particular section.

License

GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007