How to use a multi-page script without giving the eventListener error in the console?

Asked

Viewed 39 times

0

Here is a simple example to demonstrate the doubt. There are two pages and a script. I know it works by importing the script on both pages, but when I use the eventListener, it shows the error saying that it did not find the target element of the page that was not loaded. Although in this simplest example works, the error message keeps appearing on the console, and in more complex examples the event stops working.

Error message:

"Uncaught Typeerror: Cannot read Property 'addeventlistener' of null"

Page 1:

<body>
  <button id="botao1">botão 1</button>

  <script src="script.js"></script>

Page 2:

<body>
  <button id="botao2">botão 2</button>

  <script src="script.js"></script>

JS:

let botao1 = document.getElementById("botao1");
let botao2 = document.getElementById("botao2");

botao1.addEventListener("click", () => {
  alert("botao 1");
});

botao2.addEventListener("click", () => {
  alert("botao 2");
});

  • 1

    How about making a simple if? Or separate scripts? Or put JS directly in a tag script?

  • So this was an example, but the project I’m doing has an 87-line script, it wouldn’t be good practice to put it in every html. The ideal option would really be to separate the scripts, but I would like to know if it is possible to resolve this issue the way I left it there. How "if" would solve this question?

  • And validate that the button exists? if(typeof(boot 1) != 'Undefined' && boot 1 != null){ Alert('Button exists!'); botao1.addeventlistener("click", () => { Alert("boot 1"); }); } Else{ Alert('Button does not exist!');     }

  • I get it, thank you :)

  • But the code for both buttons is the same ?

1 answer

-2


Try for the JS:


botaoex.addEventListener("click", () => {
  alert("botao ex");
});

Leave the same id on both pages.

  • It’s an option. Thank you :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.