Remove anonymous keydown event

In my webpack build, I export a function

export function trapFocus(element,cb) {
  element.addEventListener('keydown', function(e) {
    ....
    //if escape is pressed, run callback function
  });
};

I’ve tried removing the keydown event listener when users hit escape

trapFocus(document.querySelector(".element"), function() {
  // doesn't work
  document.querySelector(".element").removeEventListener("keydown");
});

How can I remove this event listener? I’ve tried this, and also using .off() but I’m having trouble with this. I know how to remove event listeners from functions with names but in this case, it’s an anonymous function.

It won’t work with anonymous functions like that, you need to specify the same handler function in both adding and removing.

export function trapFocus(element, callback) {

  const keyDownHandler = function(event) {
    ...
    // pass the element and handler to the callback
    if (/* escape key */) callback(element, keyDownHandler)
  }

  element.addEventListener('keydown', keyDownHandler);
}

trapFocus(
  document.querySelector(".element"), 
  // callback receives the element and handler
  function(element, handler) {
    element.removeEventListener('keydown', handler)
  }
)

codepen

edit: It’s 3am here, so well sketchy. The above should do the trick. Just pass the element and the handler to the callback, then it has was it needs to remove that listener.

I’ll try this out shortly, thank you :slight_smile: . Makes sense to me.

1 Like

This worked great! Slight modifications to your code needed but ultimately what you provided is what I needed. Much thanks!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.