removeEventListener in a forEach loop works for 2nd element

37 Views Asked by At

I'm having an strange issue with Event Listeners, specifically removing them. In the below example I have a simple version, where I apply a mouseenter/mouseleave listener on desktop, and a click listener on mobile, however on resizing the browser, the event listener on the red box is removed correctly, but the event listener for the blue box is not.

window.addEventListener("resize", function () {sliderAnim()})

function mobileBreakpoint() {
    const isDesktop = window.innerWidth
    if (isDesktop > 650) {
      return true
    }
    if (isDesktop <= 650) {
      return false
    }
  }

let animOverDesktop, animOutDesktop, animClickMobile, animClickSection
const divs = document.querySelectorAll(".div")

function sliderAnim() {
  divs.forEach((div)=>{
    div.removeEventListener("mouseover", animOverDesktop);
    div.removeEventListener("mouseout", animOutDesktop);
    div.removeEventListener("click", animClickMobile);
  })

  
  if (mobileBreakpoint()) {
    divs.forEach((div, index) => {
      animOverDesktop = function () {
        gsap.to(div, {yPercent: 10, duration: 1})
      }

      animOutDesktop = function () {
        gsap.to(div, {yPercent: 0, duration: 1})
      }

      div.addEventListener("mouseover", animOverDesktop)
      div.addEventListener("mouseout", animOutDesktop)
    })
  }


  if (!mobileBreakpoint()) {
    divs.forEach((div, index) => {
      animClickMobile = function () {
         gsap.to(div, {xPercent: 10, duration: 1})
      }

      div.addEventListener("click", animClickMobile)
    })

  }
}
sliderAnim()

https://codepen.io/kolejain/pen/vYPKQrV

I've tried taking the removeEventListener out of the forEach function, and then it works perfectly fine. I think I'm referencing the functions correctly since this works for one of the boxes, but not the other. Is there something I'm missing here, I can't seem to find this issue anywhere else. Thank you!

0

There are 0 best solutions below