0

I'm coding along with responsive nav tutorial as it something that always gives me headaches and yet again I've hit a snag. The error I'm getting in the console states "Cannot read property 'addEventListener' of null" and it gives the line numbers. So I can see it is not registering the click event but I cannot figure out why.

Here's the js:

const navSlide = () => {
  const burger = document.querySelector('.burger');
  const nav = document.querySelector('.nav-links');

  burger.addEventListener('click', () => {
    nav.classList.toggle('nav-active');
  });
}

navSlide();

Worth noting that I'm using an html includes bit of js to insert the nav html into each page.

Everything else appears to be working i.e. CSS classes are correct when i make them visible in testing. All the nav-active class should do is add a transform: translateX(0%) to bring in the list.

Let me know if you need the HTML / CSS. Worth noting that I'm using a HTML include to include the navigation on each page but again that all works fine it's just this event listener for the click on the burger icon.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Gnatblack
  • 3
  • 1
  • The error means that `burger` is `null`, which means the code runs before the respective HTML element exists. –  Nov 10 '20 at 11:28
  • 1
    Duplicate: [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) –  Nov 10 '20 at 11:28
  • Thanks so much Chris! Weirdly, I checked the order of my scripts and the navigation js above definitely cam after the includes but I've fiddled around with it a little bit (ie.put the nav js at the very end and forgotten about the html include (its only a small site so not too big a deal) and have now got it working! I think I'll come back to it again to investigate further but for now it works so I'll get rid of this headache! Thanks again!! – Gnatblack Nov 10 '20 at 11:53

0 Answers0