Home > database >  How can I addEventListener inside of a function?
How can I addEventListener inside of a function?

Time:03-02

I'm trying to addEventListener to an HTML element with id a2, inside of a function, but Chrome Dev Tools say it's an object pointer event.

I put

    var a2 = document.getElementById("a2");

inside the function and it also doesn't work.

I would appreciate any help with this problem.

  var a1 = document.getElementById("a1");
  a1.addEventListener("click", play);

  var a2 = document.getElementById("a2");

  function play () {
      if (this.id == a1) {
          this.removeEventListener("click", play);
          a2.addEventListener("click", play);
      }
      // do something
  };  

CodePudding user response:

Removed "a2" argument from play. Same code. JSFiddle

  var a1 = document.getElementById("a1");
  a1.addEventListener("click", play);

  var a2 = document.getElementById("a2");

  function play() {
  
    console.log("a2")
    
    if (this.id == "a1") {
        console.log("a1")
      this.removeEventListener("click", play);
      a2.addEventListener("click", play);
    }
    // do something
  };
  
  • Related