2

I used this code to make my page scroll smoothly. It works well with mouse wheel. But scrolling with touchpad (Swipe with 2 fingers) behaves very fast. Please help to fix this.

Fiddle: https://jsfiddle.net/EshanRajapakshe/faLmnygp/

JS Code:

new SmoothScroll();
function SmoothScroll(el) {
  var t = this, h = document.documentElement;
  el = el || window;
  t.rAF = false;
  t.target = 0;
  t.scroll = 0;
  t.animate = function() {
    t.scroll += (t.target - t.scroll) * 0.1;
    if (Math.abs(t.scroll.toFixed(5) - t.target) <= 0.47131) {
      cancelAnimationFrame(t.rAF);
      t.rAF = false;
    }
    if (el == window) scrollTo(0, t.scroll);
    else el.scrollTop = t.scroll;
    if (t.rAF) t.rAF = requestAnimationFrame(t.animate);
  };
  el.onmousewheel = function(e) {
    e.preventDefault();
    e.stopPropagation();
    var scrollEnd = (el == window) ? h.scrollHeight - h.clientHeight : el.scrollHeight - el.clientHeight;
    t.target += (e.wheelDelta > 0) ? -70 : 70;
    if (t.target < 0) t.target = 0;
    if (t.target > scrollEnd) t.target = scrollEnd;
    if (!t.rAF) t.rAF = requestAnimationFrame(t.animate);
  };
  el.onscroll = function() {
    if (t.rAF) return;
    t.target = (el == window) ? pageYOffset || h.scrollTop : el.scrollTop;
    t.scroll = t.target;
  };
}
Eshan Rajapakshe
  • 89
  • 1
  • 1
  • 13
  • Maybe this help you https://stackoverflow.com/questions/10744645/detect-touchpad-vs-mouse-in-javascript – Saeed Apr 10 '18 at 06:37
  • You can actually adjust it in `onmousewheel` function there. e.g. `(e.wheelDelta > 0) ? -5 : 5;` to make it slower – choz Apr 10 '18 at 06:45
  • Adjust it in onmousewheel function also slows down the mouse wheel speed. That problem only for the touchpad. – Eshan Rajapakshe Apr 10 '18 at 06:55

0 Answers0