1

I would like to stop the event from listening, on the wheel after it's been executed. I can't find why the event listener is still listening.

    const scrollMe = document.querySelector('.scroll-me');
    const imgMaximmo = document.querySelector('.maximmo');
    
  
     scrollingTo = () =>{
        window.scrollTo(0,850);
         }

    cover.addEventListener('wheel', ()=>{
            cover.style.height = '105vh';
            cover.style.position = 'relative';
            cover.style.marginTop ='-52px';
            imgMaximmo.style.marginTop ='2%';
            scrollingTo(); 

    })
       cover.removeEventListener('wheel', scrollingTo, { capture: false });```
Pawel Veselov
  • 3,996
  • 7
  • 44
  • 62
ferguson_3
  • 11
  • 1
  • `cover.removeEventListener('wheel', scrollingTo);` is this not working? – Yahya Altintop Jun 15 '21 at 09:13
  • Does this answer your question? [removeEventListener on anonymous functions in JavaScript](https://stackoverflow.com/questions/4950115/removeeventlistener-on-anonymous-functions-in-javascript) – mwryl Jun 15 '21 at 09:20
  • Does this answer your question? [JavaScript: remove event listener](https://stackoverflow.com/questions/4402287/javascript-remove-event-listener) – Bladeski Jun 15 '21 at 09:21

2 Answers2

2

You're using removeEventListener incorrectly. This method accepts the same function used in addEventListener method. You subscribed to the event using anonymous function, but trying to unsubscribe using different function. So you must place your event handler function to some constant and then use it for subscribing and unsubscribing from this event. Try to change your code like this:

const scrollMe = document.querySelector('.scroll-me');
const imgMaximmo = document.querySelector('.maximmo');

// Function used inside handler
const scrollingTo = () =>{
  window.scrollTo(0,850);
}

// Handler must be set into named function to add and remove it
const wheelEventHandler = () => {
  cover.style.height = '105vh';
  cover.style.position = 'relative';
  cover.style.marginTop ='-52px';
  imgMaximmo.style.marginTop ='2%';
  scrollingTo(); 
}

// Subscribe to the event using event handler function
cover.addEventListener('wheel', wheelEventHandler);

// Unsubscribe from event using the same function
cover.removeEventListener('wheel', wheelEventHandler);
koloml
  • 525
  • 2
  • 15
0

you need to specify the same type and listener parameters to removeEventListener().

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener#matching_event_listeners_for_removal

It looks like you are passing the same type parameter, but a different listener function between addEventListener and removeEventListener

Jinw
  • 428
  • 5
  • 10