Smooth Scroll Animation in Vanilla JavaScript – moveTo.js

Category: Animation | January 15, 2019
Author: hsnaydd
Official Page: Go to Website
Last Update:August 1, 2023
License:MIT

The moveTo.js is a vanilla javascript plugin which allows adding smooth scroll animation. When a user clicks on a button or link, it will scroll to anchor section or div with nice animation.

It is dead lightweight which is about only 1kb gzipped without any dependency. The plugin works in both ways to scroll down and scroll up.

You can implement this plugin for building one website page where the navigation stay fixed at the top and when a user clicks on nav links, it goes to a specific content section.

If you need to add a page slides up or down effect then this plugin also perfect for such purpose. This effect allows users to easily go back to top of the page.

The moveTo.js  is powered by window.requestAnimationFrame() API and fully configurable with both JavaScript and Data attributes.

How to Make Scrolling Animation with Smooth Effect

First of all, you need to trigger element by pointing to the target element. You can use anchor link or an HTML button. Make sure to add class js-trigger for anchor link and for a button, you also need to define data-target.

<a href="#target" class="js-trigger">Trigger Link</a>
<!-- Or -->
<button type="button" class="js-trigger" data-target="#target">Trigger Button</button>

To make the plugin work, you need to include the main JavaScript file moveTo.min.js  before closing head element or you can also add it at the end of the HTML page.

<script src="moveTo.min.js"></script>

You can easily config the scroll animation using the ‘Data’ attributes as shown below.

<a href="#target" 
   class="js-trigger"
   data-mt-duration="300"
   data-mt-easing="easeOutQuart"
   data-mt-easing="tolerance">
   Trigger
</a>

You can also pass the options object as the second parameter to the MoveTo method.

new MoveTo({

    // The tolerance of the target to be scrolled
    tolerance: 0,

    // Duration of scrolling, in milliseconds
    duration: 800,

    // Ease function name
    easing: 'easeOutQuart',

    // run after scrolling complete
    callback: noop
    
})

Initial the function to make it work.

document.addEventListener('DOMContentLoaded', function(){
      const easeFunctions = {
        easeInQuad: function (t, b, c, d) {
          t /= d;
          return c * t * t + b;
        },
        easeOutQuad: function (t, b, c, d) {
          t /= d;
          return -c * t* (t - 2) + b;
        }
      }
      const moveTo = new MoveTo({
        ease: 'easeInQuad'
      }, easeFunctions);
      const triggers = document.getElementsByClassName('js-trigger');
      for (var i = 0; i < triggers.length; i++) {
        moveTo.registerTrigger(triggers[i]);
      }
    });

That’s it all you need to do.

2 thoughts on “Smooth Scroll Animation in Vanilla JavaScript – moveTo.js”

Comments are closed.