Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – removeEventListener not working

I am trying to add or remove EventListener using the following code.

function a(input) {
    var b = document.getElementsByClassName("class_name");
  
    if (input == "add"){
      for (let i = 0; i < 5; i++){
        b[i].addEventListener("click", c); // This is working!
      }
    }
  
    if (input == "remove"){
      for (let i = 0; i < 5; i++){
        b[i].removeEventListener("click", c); // This is not working!
      }
    }
  
    function c(d){
      random_function(e); // "e" is a global variable
      e = d.currentTarget.getAttribute("id");
      random_function(e); // Running again the same function
    }
  }

addEventListener works as expected, but removeEventListener is not working. Why is that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Every time a(input) is called, the interpreter creates a new c(d) function that has a reference different from the c(d) that was made a listener. Moving c(d) out of a(input) will solve the problem. (as long as function a can access function c)

function c(d){
  random_function(e);
  f = d.currentTarget.getAttribute("id");
  random_function(e); // Running again the same function.
}

function a(input) {
    var b = document.getElementsByClassName("class_name");
  
    if (input == "add"){
      for (let i = 0; i < 5; i++){
        b[i].addEventListener("click", c);
      }
    }
  
    if (input == "remove"){
      for (let i = 0; i < 5; i++){
        b[i].removeEventListener("click", c);
      }
    }
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading