I have a div with id "div1" that gets updated when the user presses keys. I have added an eventlistener for the keydown event that runs a function "update" and attached it to the document as follows:
let div=document.getElementById("div1");
document.addEventListener("keydown",update);
div.remove()
//event listener remains listening, because it's attached to document
When "div1" is removed from the DOM, the event listener remains. If I added the event listener to "div1", then the event listener would be removed when div1 is removed from the DOM.
let div=document.getElementById("div1");
div.addEventListener("keydown",update);
div.remove()
//event listener removed, no more listening
This approach doesn't work however, since the element has to be focused for the keydown event to trigger and my div1 doesn't have focus and I want the user to be able to update without clicking on the item anyway.
Is there a way to automatically remove the event listener when the element is deleted (as in case 2) even though the event listener is attached to the document (as in case 1). Alternatively, is there another alternative for attaching the event listener to the element and still listening for all keydown events.
You can use event delegation. Then you can check the event target in the callback to see if it matches the removed element so you can unbind the event listener.