skip to Main Content

I am trying to recreate the halo 3 UI with vanilla js, html, and css as my first solo adventure into front end web dev. Currently, I have the main menu and links to other html files. I have a single js file to handle event listeners and whatnot. I am running into an issue where i am getting a NULL reference error when trying to access elements on another page. This makes sense to me as those elements have not been rendered but the NULL error is not allowing the event listeners for the current page to work. code bellow:

/** main menu vars */
const trailer_btn = document.getElementById('show-trailer-btn');
const trailer = document.getElementById('trailer');
const trailer_escape_btn = document.getElementById('trailer-escape-btn');

/** theater menu vars */
const film_list_btn = document.getElementById('change-film-btn');
const film_list = document.getElementById('film-menu');




let trailer_playing = false;
let film_list_visible = false;



/**    MAIN MENU     */

/** event listener for trailer */
trailer_btn.addEventListener('click', ()=>{
    trailer.style.visibility='visible';
    trailer_escape_btn.style.visibility='visible';
    trailer_playing = true;
    trailer.play();
})

/**event listener to stop trailer */
trailer_escape_btn.addEventListener('click',()=>{
    trailer_playing = false;
    trailer.pause();
    trailer.currentTime = 0;
    trailer.style.visibility='hidden';
    trailer_escape_btn.style.visibility='hidden';
})


/**     THEATER PAGE     */

film_list_btn.addEventListener('click', ()=>{
    console.log('click')
    film_list.style.visibility = 'visible'
})

if i were to comment out the main menu event listeners, then the theater page event listeners will work.

so to summarize i want a single js file that will be able to handle the interactivity for all the static html pages.

I’ve commented out the main menu event listeners and because those elements are not on the theater page, it will work but if i leave them uncommented, i get a null reference error because the elements from the main menu are not rendered.

3

Answers


  1. That you need to ensure your JavaScript code checks if an element exists before trying to access it. If elements are not present on a particular page, attempting to access them will result in a NULL reference error. You can use conditional statements or other checks to handle this scenario in your code.

    Login or Signup to reply.
  2. Just check if it’s null or not …

    https://jsfiddle.net/omc32846/1/

    const trailer_btn = document.getElementById('show-trailer-btn');
    if (trailer_btn) alert(trailer_btn)
    
    const trailer_btn2 = document.getElementById('show-trailer-btn2');
    if (trailer_btn2) alert(trailer_btn2)
    
    Login or Signup to reply.
  3. can I ask for all the code you have to debug on my side? If you are ok to share it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search