removeEventListener won't remove

Advertisements

I know this question is asked a lot, but I must be overlooking something, as I can’t find a figure out why I can’t remove the event listner in the code below.

Can someone help me out? What am I missing?

function winResize() {

    viewportWidth = window.innerWidth;
    viewportHeight = window.innerHeight;

    const $sidebar = document.querySelector('.sidebar');
    const $purchaseFormFixed = document.querySelector('form.purchase-form');

    function checkFromTop() {
        ...
    }

    if ( viewportWidth >= '1000' ) {
        let sidebarHeight = $sidebar.offsetHeight;
        let space = viewportHeight - (sidebarHeight + 50);

        if ( space > '0' ) {
            window.removeEventListener('scroll', checkFromTop, false);
            $sidebar.classList.add('sticky');
            $purchaseFormFixed.classList.remove('show');
        } else {
            window.addEventListener('scroll', checkFromTop, false);
            $sidebar.classList.remove('sticky');
        }
    }

}
window.addEventListener('resize', winResize);
winResize();    

>Solution :

Move the checkFromTop function definition outside of winResize so that the same function reference is passed to removeEventListener.

Leave a Reply Cancel reply