简体   繁体   中英

Javascript remove 'focus' event listener

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

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); });

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM