javascriptevent-listenerremoveeventlistener

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?


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);
          }
        }
      }