javascriptaddeventlistenerremoveeventlistener

removeEventListener remains active even at wide widths


When the screen is smaller than 1021px, I try to add an eventListener on all navbar buttons. But when I return to a screen larger than 1020 px the eventListener remains active and I don't want it to remain active.

How should I modify the code to get what I want?

function navBarPhoneScreenClickEffect() {

    const allPhoneTabsNav = document.querySelectorAll('div.phone-tab');
    let vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);

    function test() {
        console.log('test');
    }
            
    if (vw <= 1020) {
        
        for (let i = 0; i < allPhoneTabsNav.length; i++) {
            allPhoneTabsNav[i].addEventListener('click', test)
        }
        
    } else {
        
        for (let i = 0; i < allPhoneTabsNav.length; i++) {
            allPhoneTabsNav[i].removeEventListener('click', test)
        }
        
    }

}

window.addEventListener('resize', navBarPhoneScreenClickEffect, false);

Solution

  • You need to pass the same function reference to removeEventListener as was originally pased to addEventListener. Since test is defined inside the function navBarPhoneScreenClickEffect, it's a different function each time navBarPhoneScreenClickEffect is called. Declare it outside to fix this.

    function test() {
        console.log('test');
    }
    function navBarPhoneScreenClickEffect() { 
        // ...
    }