0

I have included the code from my JavaScript file and the header.html which gets loaded into index.html with the help of <div id="header"></div>. I have all my "script src" before the closing body tag in index.html. When I try to press the button I receive the following error:

Uncaught TypeError: Cannot read property 'addEventListener' of null

I am aware that this has something to do with the way I am loading my html files. Is there a way I could solve this issue?

I am trying to keep the code redundancy more or less low and copying the whole header into every html file is not an option.

/* -- Loading assets -- */

$(document).ready(function() {
  $("#header").load("assets/header.html");
  $("#footer").load("assets/footer.html");
});

/* -- Mobile hamburger menu --*/

const hamburger = document.getElementById('hamburger');
const navList = document.getElementById('nav-list');

hamburger.addEventListener('click', () => {
  navList.classList.toggle('show');
});
/* Seperate header.html file that gets loaded into index.html */

<nav class="navbar" id="navbar">
  <p class="logo"><a href="../index.html">&lt;ŽF&#47;&gt;</a></p>

  <button class="hamburger" id="hamburger">
    <i class="fa fa-bars"></i>
  </button>

  <ul class="nav-list" id="nav-list">
    <li class="nav-item"><a href="journey.html">Link1</a></li>

    <li class="nav-item"><a href="design.html">Link2</a></li>

    <li class="nav-item"><a href="webdev.html">Link3</a></li>
  </ul>
</nav>
James Z
  • 12,209
  • 10
  • 24
  • 44
Fersek
  • 37
  • 1
  • 6
  • 1
    Either move your hamburger code inside the $.load callback (see https://api.jquery.com/load/) *or* use jquery event delegation `$("#hamburger").on("click", () => { $("#nav-list").toggle() })` – freedomn-m Sep 04 '20 at 16:59
  • Thank your response. Still not quite able to get it to work probably because I am a JavaScript beginner. It works though if I put the event delegation inside the header file but not in seperate JS file. – Fersek Sep 05 '20 at 08:22

0 Answers0