radek2s
radek2s

Reputation: 61

Remove event listener in ES6

I have following code:

document.getElementsByClassName('drag')[i].addEventListener('mousedown', (e) => {
    console.log('mousedown' + i);
});

It would be easy, if I would be able to name the function inside listener. But it's not possible in my case.

It would look like:

e.currentTarget.removeEventListener(e.type, nameFunction);

Is there any way to make it work?

Thank you.

Upvotes: 3

Views: 5705

Answers (3)

Santo Boldizar
Santo Boldizar

Reputation: 1395

There are two ways

  1. When you define a function, then add and remove the listener when you want:

    // Define a function
    const handler = () => {
        console.log('Click event...');
    }
    
    // Select the element and add event listener
    const img = document.querySelector('img');
        img.addEventListener('click', handler, false);
    
    // ...
    
    // Remove the event listener
    img.removeEventListener('click', handler, false);
    
  2. When you add an event listener and remove it on event:

    // Select the element and add event listener
    const img = document.querySelector('img');
       img.addEventListener('click', function handler(event) {
          console.log('Click event...');
    
          // On event, remove the event listener
          event.currentTarget.removeEventListener(event.type, handler);
       });
    

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 817238

It would be easy, if I would be able to name the function inside listener. But it's not possible in my case.

Don't use an arrow function if it doesn't allow you to do what you want.

document.getElementsByClassName('drag')[i].addEventListener('mousedown', function handler(e) {
    console.log('mousedown' + i);
    e.currentTarget.removeEventListener(e.type, handler);
});

Upvotes: 1

SatyaDash
SatyaDash

Reputation: 190

Yes you can write like this.

document.getElementsByClassName('drag')[i].addEventListener('mousedown', mouseDownFun);
function mouseDownFun(e){
  console.log('mousedown' + i);
}
e.currentTarget.removeEventListener(e.type, mouseDownFun);

So whenever mouse down event will be triggered it will listen in mouseDownFun.

Upvotes: 2

Related Questions