Let's programming
Let's programming

Reputation: 19

How to remove an event listener

I have nested a few event listeners into this code that will eventually link to a new page. I was going to use the same .js file on the new .html that is linked to by using the window.location method but the listeners keep on listening on the new page. How do i remove them once the new page has loaded.

I have already done a few searches online but can't find a suitable solution. Should i just create a new .js for the new page? Or is there a way to cancel all the event listeners ( There is a chunk of code for each character option)

mage.addEventListener('click', e => {
  rogue.remove();
  warrior.innerText = "Actually i don't want to be a mage, i changed my mind.";
  text.innerText = "You have chosen to be a Mage. Please click again if this is correct";
  warrior.addEventListener('click', e => {
    window.location.reload();
  });
  mage.addEventListener('click', e => {
    warrior.remove();
    text.remove();
    mage.innerText = "Let's start the adventure!"
    const char = localStorage.setItem("char", "Mage");
    mage.addEventListener('click', e => {
      window.location.href = "page1.html";
    });
  });
});

My simple interface

Upvotes: 0

Views: 191

Answers (1)

mplungjan
mplungjan

Reputation: 177685

You do NOT want to add event listeners inside an event handler

character.addEventListener('click', e => {
  const tgt = e.target.
  if (tgt.id === "mage")....
  .....  
  if (changed) window.location.reload();
});

Upvotes: 1

Related Questions