Search code examples
javascriptcssslidermousewheel

How to avoid page scrolling when scrolling slider with mouse wheel?


I developed a multiple image slider which is scrollable horizontally with mouse wheel. The problem is that when I scroll down with the mouse wheel on the page and reach the slider, although the slider starts to move from right to left, the page continues to scroll down. I want to prevent the page form further scrolling. I tried to put "overflow: hidden" on the body while the mouse is over the slider, but then the slider jumps because of the scroll disappearing and reappearing. Does anybody have an idea how could I solve this? Thank you in advance.

  sliderWrapper.addEventListener('wheel', () => {
           
    let sliderLeft = firstImg.getBoundingClientRect().left;
    let sliderWrapperLeft =  sliderWrapper.getBoundingClientRect().left;

    let sliderRight = lastImg.getBoundingClientRect().right;
    let sliderWrapperRight =  sliderWrapper.getBoundingClientRect().right;

    function detectMouseWheelDirection(e) {
      var delta = null,
        direction = false;
      if (!e) {
        // if the event is not provided, we get it from the window object
        e = window.event;
      }
      if (e.wheelDelta) {
        // will work in most cases
        delta = e.wheelDelta / 60;
      } else if (e.detail) {
        // fallback for Firefox
        delta = -e.detail / 2;
      }
      if (delta !== null) {
        direction = delta > 0 ? 'up' : 'down';
      }

      return direction;
    }

    function handleMouseWheelDirection(direction) {
      // if mousewheel direction is down, move the slider to the left
        
       if (direction == 'down' && sliderRight > sliderWrapperRight) {
        innerSlider.style.left = --count * 15 + '%';
        // if mousewheel direction is up, move the slider to the right
      } else if (direction == 'up' && sliderLeft <= sliderWrapperLeft) {
        innerSlider.style.left = ++count * 15 + '%';
      } else {
        innerSlider.style.left = 0 + '%';
        count = 0;
      }
            
    }

   document.onmousewheel = function (e) {
      if (isMouseHover) {
          handleMouseWheelDirection(detectMouseWheelDirection(e));
      }
    };

    if (window.addEventListener) {
    document.addEventListener('DOMMouseScroll', function (e) {
        handleMouseWheelDirection(detectMouseWheelDirection(e));
      });
    }
  });

Solution

  • Just prevent the default behavior of the event and it's propagation in your sliderWrapper event listener for the wheel: pass it as a parameter for the listener function, and then

    e.preventDefault();
    e.stopPropagation();