Search code examples
javascriptfor-loopdrag

Can't add Loop to Drag Scroll Slider without breaking the dragging functionality


I've just followed this tutorial on Youtube to add a drag scroll to any scroll elements (https://www.youtube.com/watch?v=C9EWifQ5xqA&t=115s&ab_channel=WesBos) It worked and was extremely helpful. My only issue is I would like to apply this to multiple sliders on one page. I believe I have to create some form of 'For Loop' but I'm struggling to get anything working. Whenever I seem to add a For Loop it breaks the functionality and stops working.

Heres the JS I currently have which works.

var scrollSlider = document.querySelector(".scroll-slider1, .scroll-slider2");
let isDown = false;
let startX;
let scrollLeft;
 
scrollSlider.addEventListener('mousedown', (e) => {
    e.preventDefault();
    isDown = true;
    scrollSlider.classList.add('active');
    startX = e.pageX;
    scrollLeft = scrollSlider.scrollLeft;
});

scrollSlider.addEventListener('mouseleave', () => {
    isDown = false;
    scrollSlider.classList.remove('active');
});

scrollSlider.addEventListener('mouseup', () => {
    isDown = false;
    scrollSlider.classList.remove('active');
});

scrollSlider.addEventListener('mousemove', (e) => {
    e.preventDefault();
    if(!isDown) return;
    const x = e.pageX;
    const scroll = x - startX;
    scrollSlider.scrollLeft = scrollLeft - scroll;
});

Could anyone help me add some form of loop to this, so it gets applied to every drag slider on the page rather than just the first slider? Thanks.


Solution

  • // Get all scroll sliders
    const scrollSliders = document.querySelectorAll(".scroll-slider1, .scroll-slider2");
    
    // Loop through each scroll slider
    scrollSliders.forEach(scrollSlider => {
      let isDown = false;
      let startX;
      let scrollLeft;
     
      // Add event listeners for each scroll slider
      scrollSlider.addEventListener('mousedown', (e) => {
          e.preventDefault();
          isDown = true;
          scrollSlider.classList.add('active');
          startX = e.pageX;
          scrollLeft = scrollSlider.scrollLeft;
      });
    
      scrollSlider.addEventListener('mouseleave', () => {
          isDown = false;
          scrollSlider.classList.remove('active');
      });
    
      scrollSlider.addEventListener('mouseup', () => {
          isDown = false;
          scrollSlider.classList.remove('active');
      });
    
      scrollSlider.addEventListener('mousemove', (e) => {
          e.preventDefault();
          if(!isDown) return;
          const x = e.pageX;
          const scroll = x - startX;
          scrollSlider.scrollLeft = scrollLeft - scroll;
      });
    
    });