0

I have a javasrcipt code to make draggable som horozontal scroll areas on a website i'm working on, which works well on the first elemnt in dom, but i have more of such areas with the same class, and i was trying to looping through them all, but after gooogling a few hours and making several attemps a just couldn't make it work, could please help me how should i modify my code. Here is the code which works on the first dom element:

const slider = document.querySelector(".ld-products ul");
let isDown = false;
let startX;
let scrollLeft;

slider.addEventListener("mousedown", e => {
    clearTimeout(this.downTimer);
    this.downTimer = setTimeout(function() {
        slider.classList.add("active");  
    }, 100); 
  isDown = true;
  
  startX = e.pageX - slider.offsetLeft;
  scrollLeft = slider.scrollLeft;
});
slider.addEventListener("mouseleave", () => {
  isDown = false;
  slider.classList.remove("active");
});
slider.addEventListener("mouseup", () => {
  isDown = false;
  slider.classList.remove("active");
});
slider.addEventListener("mousemove", e => {
  if (!isDown) return;
  e.preventDefault();
  const x = e.pageX - slider.offsetLeft;
  const walk = x - startX;
  slider.scrollLeft = scrollLeft - walk;
});

1 Answers1

0

Put the code inside a loop over all the matching elements.

const sliders = document.querySelectorAll(".ld-products ul");

sliders.forEach(slider => {
  let isDown = false;
  let startX;
  let scrollLeft;

  slider.addEventListener("mousedown", e => {
    clearTimeout(this.downTimer);
    this.downTimer = setTimeout(function() {
      slider.classList.add("active");
    }, 100);
    isDown = true;

    startX = e.pageX - slider.offsetLeft;
    scrollLeft = slider.scrollLeft;
  });
  slider.addEventListener("mouseleave", () => {
    isDown = false;
    slider.classList.remove("active");
  });
  slider.addEventListener("mouseup", () => {
    isDown = false;
    slider.classList.remove("active");
  });
  slider.addEventListener("mousemove", e => {
    if (!isDown) return;
    e.preventDefault();
    const x = e.pageX - slider.offsetLeft;
    const walk = x - startX;
    slider.scrollLeft = scrollLeft - walk;
  });

});
Barmar
  • 741,623
  • 53
  • 500
  • 612