简体   繁体   中英

document.body.removeEventListener not working for removing listener for keypress event

I am adding a event listener which listens for Escape keypress and closes the image modal, but on Escape keypress image modal closes but event listener do not removes. Here's my code. Please tell me how to come up with this issue.

function closeImgModal() {
    imgModal.style.display = "none";
    document.body.style.overflowY = "auto";
    document.body.removeEventListener('keydown', closeImgModal)
}

function openBig(el) {
    document.body.style.overflowY = "hidden";
    imgModal.style.display = "block";
    randomImg.src = el.src;
    document.body.addEventListener('keypress', function (e) {
        console.log(e);
        if (e.key === "Escape") {
            closeImgModal();
        }
    });
}

To remove a listener the event names need to be the same. You have keyup vs keypress.

The handler function reference also needs to be the same. For that to happen you will need a named function which I created from the anonymous function used in your addEventlistener and called it handleKeypress

Now the parameters used for add/remove are identical as required

function closeImgModal() {
  imgModal.style.display = "none";
  document.body.style.overflowY = "auto";
  document.body.removeEventListener('keypress', handleKeypress)
}

function handleKeypress(e) {
  console.log(e);
  if (e.key === "Escape") {
    closeImgModal();
  }
}

function openBig(el) {
  document.body.style.overflowY = "hidden";
  imgModal.style.display = "block";
  randomImg.src = el.src;
  document.body.addEventListener('keypress', handleKeypress);
}

try this

 function closeImgModal() { imgModal.style.display = "none"; document.body.style.overflowY = "auto"; document.body.removeEventListener('keypress', closeImgModal) } function openBig(el) { document.body.style.overflowY = "hidden"; imgModal.style.display = "block"; randomImg.src = el.src; document.body.addEventListener('keypress', function (e) { console.log(e); if (e.key === "Escape") { closeImgModal(); } }); }

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