How can I stop slider moved by mouse wheel at the last image?

109 Views Asked by At

I am working on a multi-image slider (i.e. several images appear next to each other at the same time and move together) that can be moved with the mouse wheel. I detect the direction of the mouse wheel (up or down) and the slider moves to the left or the right accordingly. It works quite well, the only problem is that I can't get the last picture to stop at the edge of the slider, so it doesn't jump inside if you roll a bigger with the mouse wheel (same for the first picture if you scroll backwards). I would be really grateful for some assistance. Thank you in advance. This is my JS code:

  // move slider on mouse wheel scrolling depending on mouse wheel direction
  aboutSliders[i].addEventListener('wheel', () => {
    // let slideWidth = firstImg.getBoundingClientRect().width;

    // get the first slide's position from left side of screen
    let sliderLeft = firstImg.getBoundingClientRect().left;
       // get the slider wrapper's position from left side of screen
    
    let sliderWrapperLeft = aboutSliders[i].getBoundingClientRect().left;

        // get the last slide's position from left side of screen
    let sliderRight = lastImg.getBoundingClientRect().right;
      // get the slider wrapper's position from left side of screen
    let sliderWrapperRight = aboutSliders[i].getBoundingClientRect().right;

    // detect mouse wheel's direction (up or down) 
    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' and the slider wrapper's position is not further to the right than the last slide's, move the slider to the left
      if (direction == 'down' && sliderRight >= sliderWrapperRight) {
        innerSlider.style.marginLeft = --count * 5 + '%';

        // if mousewheel direction is 'up', and the slider wrapper's position is not further to the left than the first slide's, move the slider to the right
      } else if (direction == 'up' && sliderLeft <= sliderWrapperLeft) {
        innerSlider.style.marginLeft = ++count * 5 + '%';
      }
    }

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

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

There are 0 best solutions below