Scroll to element with effect

ES6 and lodash required. Maybe you can convert it to ES5.


usage.js
import scrollTo from './scrollTo';

scrollTo('reviews', -50, 1000).then(() => alert('scroll ended'))
scrollTo.js
import isString from 'lodash/isString';

function scrollTo(element, to, duration, resolve) {
  if (duration <= 0) return resolve();
  var difference = to - element.scrollTop;
  var perTick = difference / duration * 10;

  setTimeout(function() {
    element.scrollTop = element.scrollTop + perTick;
    if (element.scrollTop === to) return resolve();
    scrollTo(element, to, duration - 10, resolve);
  }, 10);
}

export default (to, offset = 0, duration = 150) => {
  const element = isString(to) ? document.getElementById(to) : to;

  return new Promise(resolve => {
    scrollTo(document.body, document.body.scrollTop + element.getBoundingClientRect().top + offset, duration, resolve);
  });
}

Share This Post