Search code examples
javascriptdomevent-listener

Why use removeEventListener vs just deleting it?


I'm learning JavaScript and the methods to interact with the DOM.

I got to event listeners and saw that there is a removeEventListener() method.

I understood how to use it but was curious as to why we don't just delete the line of code with the event listener we don't want? Is there a reason as to why it is better to use the remove method over just removing ourselves?

Any clarification on this would be helpful :)

Thanks


Solution

  • You might want to add a listener to an element, then remove the listener later. You don't want to remove the listener code entirely because then the listener won't fire during the interval you want it to.

    const button = document.querySelector('button');
    button.addEventListener('click', () => {
      const listener = () => console.log('hovered');
      button.addEventListener('mouseover', listener);
      setTimeout(() => {
        console.log('listener removed');
        button.removeEventListener('mouseover', listener);
      }, 2000);
    });
    <button>click to enable hover listener</button>

    To implement the logic above, addEventListener is required - you can't just delete that section. But you also want to remove the listener later, so removeEventListener is needed too.