Search code examples
javascriptarraysloopsgsap

Iterating through 2 arrays in javascript (gsap)


I am having trouble iterating through 2 arrays to change my gsap timeline.

const subTabs = Array.from(document.querySelectorAll(".subtab"));
const expandTabs = Array.from(document.querySelectorAll(".expandtab"));
const tl = gsap.timeline({ defaults: { duration: 1, yoyo: true, } });

tl.set(expandTabs, {
    visibility: "hidden",
    opacity: 0,
    scale: 0,
});

I need the index values to correspond, for example, if subTabs[0] is "mouseover" then expandTabs[0] needs to have the new animations applied to it. Vice versa with "mouseout". What am I doing wrong here?

subTabs.forEach((subTab, index) => {
    const expandTab = expandTabs[index];
    console.log(subTab, expandTab);

    // Event Listener Hover on
    subTab.addEventListener("mouseover", (event) => {
        console.log("you clicked region number " + index);
        tl.to(expandTab[index], {
            visibility: "visible",
            opacity: 1,
            scale: 1,
        });
    });

    // Event Listener Hover off
    subTab.addEventListener("mouseover", (event) => {
        console.log("you exited region number " + index);
        tl.to(expandTab[index], {
            visibility: "hidden",
            opacity: 0,
            scale: 0,
        });
    });
});

Solution

  • Perhaps your second listener should be mouseout instead of another mouseover.

    subTab.addEventListener("mouseout", (event) => {
    

    In regards to the index issue, why not used an generated id instead to retrieve the element?

    As is, your line here might work better as:

    tl.to(expandTab, {
                visibility: "visible",
                opacity: 1,
                scale: 1,
            });