-1

I have a button in HTML that I am adding an event listener for in JavaScript.

<button class="Button" id="First" type="button">Confirm First Location</button>
map.addListener("click", (mapsMouseEvent) => {
      document.getElementById("First").style.visibility = "visible"
  }

  document.getElementById("First").addEventListener("click", function() {
    console.log("button clicked")
  });

The button is hidden by default and I want to add the event listener after the user interacts with a map. However, after the button becomes visible, I get an error saying Cannot read properties of null (reading 'addEventListener'), even though the element exists, as shown by it becoming visible.

However, if I add the event listener inside the maplistener function:

map.addListener("click", (mapsMouseEvent) => {
      document.getElementById("First").style.visibility = "visible"
      document.getElementById("First").addEventListener("click", function() {
        console.log("clicked")
      });
  }

the eventListener works. I'm confused as to why this would work in the mapListener function, and not on its own. Please let me know.

BVB44
  • 266
  • 2
  • 11
  • its `addEventListener` not `addListener` – skara9 Dec 25 '21 at 06:08
  • @skara9 I have no problems with the map.addListener, that is from the Google API and it is correct. The issue is with the document.getElementById("First").addEventListener – BVB44 Dec 25 '21 at 06:14
  • where is your script tag? make sure its either at the bottom of the body or deferred – skara9 Dec 25 '21 at 06:17
  • @skara9 The JS is in a separate file, `````` – BVB44 Dec 25 '21 at 06:18
  • Most likely in the first case the script runs before the DOM is fully populated, in this case perhaps the ` – tromgy Dec 25 '21 at 06:21
  • @tromgy In my HTML, I configure my JS script source in the head, which is above the – BVB44 Dec 25 '21 at 06:24
  • 1
    It depends. The scripts that are imported in the head are usually some libraries that don't depend on the DOM. Your own scripts that depend on the DOM should be placed at the bottom of the `` tag, that is just before `` – tromgy Dec 25 '21 at 06:26
  • 1
    @BVB44 https://stackoverflow.com/questions/196702/where-to-place-javascript-in-an-html-file – Brendan Bond Dec 25 '21 at 06:27
  • @BrendanBond thank you for the link, the solution worked! Happy Holidays – BVB44 Dec 25 '21 at 06:31
  • @tromgy just tried that and it fixed the issue, thank you! Happy Holidays – BVB44 Dec 25 '21 at 06:32

2 Answers2

1

Fixed by placing scripts below the body tag

BVB44
  • 266
  • 2
  • 11
0

I think u just missed a little thing...a Typographical mistakes;)

use:

map.addEventListener("click", (mapsMouseEvent) => {
    document.getElementById("First").style.visibility = "visible"
}

instead of:

map.addListener("click", (mapsMouseEvent) => {
    document.getElementById("First").style.visibility = "visible"
}
3h54n75
  • 76
  • 3