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