So I have a horizontal scrolling feature which works great in JS but only for one section with the classname, any other section that shares the same classname it doesn’t replicate the same effects for. How can I make it so it works for every section that has the class name. You can see it in action on my website here where the quick links scrolls fine when you click but the other horizontally scrolling sections dont. Thank you – https://tutoryou.uixweb.dev/
const slider = document.querySelector('.scroller-div');
let mouseDown = false;
let startX, scrollLeft;
let startDragging = function (e) {
mouseDown = true;
startX = e.pageX - slider.offsetLeft;
scrollLeft = slider.scrollLeft;
};
let stopDragging = function (event) {
mouseDown = false;
};
slider.addEventListener('mousemove', (e) => {
e.preventDefault();
if(!mouseDown) { return; }
const x = e.pageX - slider.offsetLeft;
const scroll = x - startX;
slider.scrollLeft = scrollLeft - scroll;
});
// Add the event listeners
slider.addEventListener('mousedown', startDragging, false);
slider.addEventListener('mouseup', stopDragging, false);
slider.addEventListener('mouseleave', stopDragging, false);
2
Answers
First change this:
To this:
querySelector
will stop after finding the first element matching your selector while querySelectorAll will return a list of all the elements matching your selector.Once you do that, you will need to loop through all the sliders and add the event listener to each one. So your code becomes wrapped in a
forEach
loop:for smooth scrolling (no jump effect) you have to create variables inside
forEach()