Reputation: 61
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
Reputation: 1395
There are two ways
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);
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
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
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