Search code examples
javascriptjoomlatypeerrorresponsive

Uncaught TypeError: Cannot read property 'classList' of null at HTMLDivElement.<anonymous>


I'm facing an issue with the error described in the title of my question. When I click on the burger for my mobile menu, this error message comes up: Uncaught TypeError: Cannot read property 'classList' of null at HTMLDivElement.. Here is my JS Code:

window.onload = function(){
const navSlide = () => {
    const burger = document.querySelector('.burger');
    const nav = document.querySelector('.nav-links');
    const navLinks = document.querySelectorAll('.nav-links li');
    
    burger.addEventListener('click', () => {
        // Toggle Nav
        nav.classList.toggle('nav-active');

        // Animate Links
        navLinks.forEach((link, index) => {
            if (link.style.animation) {
                link.style.animation = '';
            } else {
                    link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.5}s`;
                }
        });
        // Burger Animation
        burger.classList.toggle('toggle');

    });
    
}

navSlide();

}

,... this is my HTML:

<header>
  <div class="logo">
    <h1 class="logo-text">Title</h1>
  </div>
  <ul class="nav">
    <li><a href="#">Home</a></li>
    <li><a href="#">Item1</a></li>
    <li><a href="#">Item2</a></li>
    <li><a href="#">Item3</a></li>
  </ul>

  <div class="burger">
    <div class="line1"></div>
    <div class="line2"></div>
    <div class="line3"></div>
  </div>
</header>

In CSS I have a class called .nav-active and a class .toggle which should work when I open the menu. I'm using this JS as an additional file in Joomla.

I hope you can help me! Thank you!


Solution

  • Your class is incorrect

    const nav = document.querySelector('.nav-links');
    const navLinks = document.querySelectorAll('.nav-links li');
    

    but you use:

    <ul class="nav">
    

    So when

    nav.classList.toggle('nav-active');
    

    is called, the "nav" object is not defined.

    Change the unordered list to:

    <ul class="nav-links">