I have a scroll script that scrolls left or right when an icon is clicked. Works great too. But now I have several elements on one page. Only the first element works.
Somehow I don’t know anymore. Who can help?
var myEle = document.getElementsByClassName("test-js");
if(myEle) {
const gallery = document.querySelector('.test-js');
const gallery_scroller = gallery.querySelector('.horizontal-scroll-js');
const gallery_item_size = gallery_scroller.querySelector('div').clientWidth - 60;
gallery.querySelector('.icon-scroll-next').addEventListener('click', scrollToNextPage);
gallery.querySelector('.icon-scroll-nrev').addEventListener('click', scrollToPrevPage);
function scrollToPrevPage() {
gallery_scroller.scrollBy(-gallery_item_size, 0);
}
function scrollToNextPage() {
gallery_scroller.scrollBy(gallery_item_size, 0);
}
}
2
Answers
Turn it into a function and apply it to multiple instances:
Now you can call
gallery
as many times as you need to!class name or attributes or id doesn’t matter for event listening. you can register event listeners for all elements with or without same classname. important part is to target correct elements.
There are several ways to fix your problem but I don’t know about your HTML tree.
FYI;
var myEle = document.getElementsByClassName("test-js");
andconst gallery = document.querySelector('.test-js');
selects the same element which is the 1st element with test-js class.I’ll use @somethinghere’s solution;
keep in mind; this method would work fine only in the condition that no other element in DOM has "test-js" class. It is better/safer to target elements with ids, specific attributes or class combinations etc.
Also I assume that your test-js parentNode contains all relevant childNodes.