2

I want to remove 'focus' event listener from element using plain javascript but not working

document.getElementById("txttaskdateDeploy").removeEventListener("focus", function(e){});

but below jquery works

$("#txttaskdateDeploy").unbind("focus");

can anyone tell why its not working in plain javascript

Sunil kumar
  • 317
  • 1
  • 9
  • 19
  • 1
    Possible duplicate of [How do you clear the focus in javascript?](https://stackoverflow.com/questions/2520650/how-do-you-clear-the-focus-in-javascript) – Arnab Roy Apr 04 '19 at 11:01
  • 1
    You are creating a new function when you should pass an existing listener. `function(e){}` creates a new function which was not a listener before. – Roberto Zvjerković Apr 04 '19 at 11:02
  • @ArnabRoy — No. The question is about removing the focus **event listener** not the focus itself. – Quentin Apr 04 '19 at 11:08

2 Answers2

6

The second argument you pass to removeEventListener has to be the function you want to remove.

You have a function expression there, so it will create a brand new function. Since it is a new function, it can't match any of the existing event listeners, so none of them will be removed.

This could work:

const x = function (e) { console.log(1); };
foo.addEventListener("focus", x);
foo.removeEventListener("focus", x);

But this won't (two different but identical functions are not the same function):

foo.addEventListener("focus", function (e) { console.log(1); });
foo.removeEventListener("focus", function (e) { console.log(1); });
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
3

You need to pass the specific event listener that you want to remove to the removeEventListener method, instead of just passing an empty function.

An example of how this should be done would be:

const listener = function(e) {
  console.log('focused!'); // do anything here
} 

// Add event listener 
document.getElementById("txttaskdateDeploy").addEventListener("focus", listener);

// When you want to remove the event listener 
document.getElementById("txttaskdateDeploy").removeEventListener("focus", listener);
natsuozawa
  • 565
  • 5
  • 10