0

I am wondering if someone can help me alter this code so that it resets or works with multiple elements?

On the website below I have this script set up to scroll right by 100vw Using the window.scrollBy(window.innerWidth /1, 0); when the purple box is hovered over.

however I would like it to work with multiple instances and can't seem to get it to work. Is anyone able to help me?

here is my script;

let button = document.getElementById("mybutton");

button.addEventListener("mouseover", () => {
window.scrollBy(window.innerWidth /1, 0); 
});

and her is the url: https://ba-site-build.webflow.io/builds/dev-1-hover-slider.

i would really appreciate if anyone can offer any help so much!

Thankyou :)

1 Answers1

0

The problem is that id of elements must be unique, So you can use class instead and in the script loop over elements and add event listener for all of them.

HTML:

    <div class="horizontal">

        <div class="red">
            <div class="scrollThis button">
                <div class="purple"></div>
            </div>
        </div>

        <div class="red">
            <div class="scrollThis button">
                <div class="purple"></div>
            </div>
        </div>

        <div class="yellow"></div>
    </div>

JS:

let buttons = document.getElementsByClassName("scrollThis");

for (let item of buttons) {
    item.addEventListener("mouseover", () => {
        window.scrollBy(window.innerWidth /1, 0); // <-- you can change this amount if you need more than 120px
    });
}

I hope this helps you.

Ashkan
  • 272
  • 2
  • 11