Home > Back-end >  Error Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') in a
Error Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') in a

Time:04-17

This error keep showing to me only if a put this JavaScript code in a separeted file, and link to my Html... If they are insede a tag they work just fine...

script.js:4 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

Html:

<div  id="mobile-menu">
                <span ></span>
                <span ></span>
                <span ></span>
            </div>
            <ul >
                <li >
                    <a href="#me" ><span>01. &nbsp;</span> About me </a>
                </li>
                <li >
                    <a href="#work" ><span>02. &nbsp;</span> Projects</a>
                </li>
            </ul>

JavaScript:

console.log("out of script");
let menu = document.querySelector('#mobile-menu');
let menuLinks = document.querySelector(".navbarr__menu");
menu.addEventListener('click', function(){
    console.log("!I here");
    menu.classList.toggle('is-active');
    menuLinks.classList.toggle('active');
    
})

What can be the issue here? note that I alredy link the .Js file to my .Html...

CodePudding user response:

Most likely you have issues with connecting script.js to your html file. You either need to connect js file after </body> tag or check if html content is ready/rendered with DOMContentLoaded event inside of your js file, and when DOM content is loaded you can execute your js code. Should be fine then.

  • Related