Scroll function works fast in mac and touchpad

Viewed 363

I have a slider and I made a code that goes next and prev with mouse scroll. But it doesn't work well with mac and touchpad. how can I fix it? Can I put some delay or something I tried to use some setTimeout but it didn't work well or I didn't do it right.

$('#body').on('mousewheel', function (event) {
  if (typeof event.originalEvent.wheelDeltaY === 'undefined') {
    console.log("could not find mouse deltas")
  }
  var deltaY = event.originalEvent.wheelDeltaY;
  var scrolledUp = deltaY < 0;
  var scrolledDown = deltaY > 0;
  if (scrolledDown) {
    if (swiper_color.activeIndex > 2) {
      goTop();
      activeIndexToTwo();
    } else {
        swiper_color.slidePrev();
        swiper_image.slidePrev();
        swiper_desc.slidePrev();
        swiper_title.slidePrev();
        swiper_jar.slidePrev();
    }
  }
  if (scrolledUp) {
    if (swiper_color.activeIndex < 2) {
      swiper_color.slideNext();
      swiper_image.slideNext();
      swiper_desc.slideNext();
      swiper_title.slideNext();
      swiper_jar.slideNext();
    } else {
      checkscroll();
    }
  }
});
1 Answers

I'd recommend throttling the function. You could write a throttle function, or use one from a library like Lodash (Lodash throttle docs)

function yourFn (event) {
  // ... all of your js here
  // ...
}

$('#body').on('mousewheel', _.throttle(yourFn, 100));

The 100(ms) above means your function can only fire every 100ms, feel free to modify the time to your liking.

Related