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

How can I addEventListener inside of a function?

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.

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

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

>Solution :

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