Reputation: 130
i want to ask you, how to remove an event listener with arrwo functions ? I tried some methods here but not worked Any Solution ?
add.addEventListener("click" , ()=> {
let b = document.createElement("input");
b.setAttribute("id" , "dif");
b.type = "number";
b.placeholder = "Write Third Number";
calc.append(b);
})
add.removeEventListener("click" );
Upvotes: 1
Views: 1771
Reputation: 189
The reason it doesn't work is because removeEventListener
requires that you pass as argument both the type of event (e.g. click) and the event listener function to be removed (the arrow function).
The reason you must provide both is because you could attach multiple event listeners for the same event for the same event.
To make it work, you have two solutions:
function doSomethingOnClick() {
// Do some stuff
}
element.addEventListener('click', doSomethingOnClick);
// later ...
element.removeEventListener('click', doSomethingOnClick);
const doSomethingOnClick = () => console.log('Doing some stuff ...');
element.addEventListener('click', doSomethingOnClick);
// later ...
element.removeEventListener('click', doSomethingOnClick);
For more information, have a look at Mozilla's documentation
Upvotes: 1
Reputation: 741
In order to remove you would need a reference to the callback you gave for the add, so you would need to declare the function outside and give it to the add event listener and then remove it:
let myClick = ()=> {
let b = document.createElement("input");
b.setAttribute("id" , "dif");
b.type = "number";
b.placeholder = "Write Third Number";
calc.append(b);
};
add.addEventListener("click" , myClick ):
add.removeEventListener("click", myClick );
Upvotes: 3
Reputation: 782148
If you want to use removeEventListener
, you need to use a named function when adding.
function listener () {
let b = document.createElement("input");
b.setAttribute("id" , "dif");
b.type = "number";
b.placeholder = "Write Third Number";
calc.append(b);
}
add.addEventListener("click", listener);
...
add.removeEventListener("click", listener);
Upvotes: 1