Reputation: 11
Trying to remove event listeners from the keydown and click events, but my code seems to not be working. Not sure where the problem is; new to JS and trying to sort it out. Do I need to move the removeEventListeners outside the function?
const togglePopupAlt = () => {
const popupList = Array.from(document.querySelectorAll(".popup"));
popupList.forEach((modal) => {
modal.addEventListener("click", (evt) => {
togglePopup(evt.target);
});
});
popupList.forEach((modal) => {
modal.removeEventListener("click", (evt) => {
togglePopup(evt.target);
});
});
popupList.forEach(() => {
document.addEventListener("keydown", (evt) =>{
const escKey = 27;
if (evt.keyCode === escKey){
togglePopup(document.querySelector(".popup_active"));
}
});
document.removeEventListener("keydown", (evt) =>{
const escKey = 27;
if (evt.keyCode === escKey){
togglePopup(document.querySelector(".popup_active"));
}
});
});
}
togglePopupAlt();
Upvotes: 0
Views: 1946
Reputation: 1112
You need to pass in the same handler in removeEventListener
that you are passing in addEventListener
const handler = () => doSomeThing()
element.addEventListener("click", handler)
// Then remove them like this.
element.removeEventListener("click", handler)
Since you are creating a new function every time you loop, store those handlers in an array and use the same handlers in the removeListener
for each element.
Since the logic of the handlers are same for all elements you can do this:
const modalHandler = (evt) => {
togglePopup(evt.target);
};
const keyDownHandler = (evt) => {
const escKey = 27;
if (evt.keyCode === escKey) {
togglePopup(document.querySelector(".popup_active"));
}
};
const togglePopupAlt = () => {
const popupList = Array.from(document.querySelectorAll(".popup"));
popupList.forEach((modal) => {
modal.addEventListener("click", modalHandler);
});
popupList.forEach((modal) => {
modal.removeEventListener("click", modalHandler);
});
popupList.forEach(() => {
document.addEventListener("keydown", keyDownHandler);
document.removeEventListener("keydown", keyDownHandler);
});
};
togglePopupAlt();
Upvotes: 2
Reputation: 65806
When you remove an event listener, you must pass a reference to the function that was set up as the handler, therefore you can't remove event listeners that were added as anonymous functions. Only named functions can be removed.
function handler(){
console.log("Handled!");
}
document.querySelector("button").addEventListener("click", handler);
document.getElementById("remove").addEventListener("click", function(){
document.querySelector("button").removeEventListener("click", handler);
});
<button>Click Me</button>
<button id="remove">Remove Handler</button>
Upvotes: 0