Albenis Kërqeli
Albenis Kërqeli

Reputation: 130

Remove Event Listener , arrow function

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

Answers (3)

B Thuy
B Thuy

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:

  1. Extract the arrow function to a named function. For example:
function doSomethingOnClick() {
// Do some stuff
}

element.addEventListener('click', doSomethingOnClick);

// later ...

element.removeEventListener('click', doSomethingOnClick);
  1. Assign your arrow function to a variable. For example:
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

audzzy
audzzy

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

Barmar
Barmar

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

Related Questions