Jump to content

Plain JavaScript animated window scroll function

Posted in JavaScript · 2 minutes read

Before modern frameworks, I always used jQuery's scrollTo method. At some point, not every project included jQuery, so I wrote simple function to animate window scroll.

I have kept copying that function from project to project. Finally I took some time, cleaned it up and published it on the npm (this is the first npm package I published).

Check the demo and read documentation of Github.

Find it on Github and npm

Installation #

npm install animated-scroll-to

Usage #

import animateScrollTo from 'animated-scroll-to';

// desiredOffset - page offset to scroll
// options - object with options

// default options
const options = {
  // duration of the scroll per 1000px, default 500
  speed: 500,

  // minimum duration of the scroll
  minDuration: 250,

  // maximum duration of the scroll
  maxDuration: 1500,

  // DOM element to scroll, default window
  // Pass a reference to a DOM object
  // Example: document.querySelector('#element-to-scroll'),
  element: window,

  // should animated scroll be canceled on user scroll/keypress
  // if set to "false" user input will be disabled until animated scroll is complete
  cancelOnUserAction: true
};

const desiredOffset = 1000;

animateScrollTo(desiredOffset, options);

Comments (2)

16. November 2016
Maison Armani

Thanks... Just used it, works fine and the code is clean

19. October 2016
Vojin

Really cool stuff-nice and clean :)