1

I've created a website that has index.html and quiz.html, one style.CSS and one app.JavaScript.

I have added some functions in the JS that refer to both pages. Lets say: Page 1 index.html: the app.js has an event listener to show a box on click. That box then has a button to move to quiz.html (all works fine). Page 2 quiz.html: on JavaScript I have functions to make the quiz run. The problem is that the code breaks before it gets to the functions for the quiz, with a line referring to the first page.

Error: app.js:14 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at app.js:14:35

Line 14 is document.getElementById('btnPlay').addEventListener('click', openBox), that refers to an element within index.html, not the page I am now quiz.html.

I understand why, because on this current page we don't have a reference to it. But I have read in many places that is usually better to use one app.js file and not one per html page. How do we make this work? Any suggestions?

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • Use `document.getElementById('btnPlay')?.addEventListener('click', openBox)` – Roko C. Buljan Feb 25 '22 at 23:08
  • We cannot see your code or your HTML so we will be much less likely to best answer your question here. You could check for the existence on the page (a few ways to do that) before adding the listener.. – Mark Schultheiss Feb 25 '22 at 23:12
  • 1
    Hey Mark! It's my first time posting, what would be a best practice? Because I posted the lines affected, but I didn't think would be useful to copy past all my code. Or would it be? Thanks! – Maria Alpuim Feb 25 '22 at 23:16

1 Answers1

1

On some page B you don't have that #btnPlay Element therefore document.getElementById('btnPlay') equals undefined. And you cannot assign an event listner to it: undefined.addEventListener.

To make sure that element exists — before moving forward
use Optional Chaining ?..

document.getElementById('btnPlay')?.addEventListener('click', openBox)

otherwise on page B the "#btnPlay" is not found and your JavaScript will break.


Another "old" way to tackle that issue would've been using a statement:

const EL_btnPlay = document.querySelector("#btnPlay"); 
if (EL_btnPlay) EL_btnPlay.addEventListener("click", openBox);

where the aforementioned is just a shorthand to do the same.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313