0

I’m doing a portofolio with Dash plotly,

so, i use a lot of sass and js for making pretty.

but i have a problem.

on my assets/script.js have

const menuIcon = document.querySelector('#menu-icon');
const navbar = document.querySelector('.navbar');

console.log(menuIcon);
console.log(navbar);

menuIcon.onclick = () => {
    menuIcon.classList.toggle('bx-x');
    navbar.classList.toggle('active');
};

and get this error:

null
null
sripts.js:12 Uncaught TypeError: Cannot set properties of null (setting 'onclick')
    at scripts.js:12:18

if i set a timer, works fine:

*==== toggle navbar icon =====*/
setTimeout(() => {

    const menuIcon = document.querySelector('#menu-icon');
    const navbar = document.querySelector('.navbar');

    console.log(menuIcon);
    console.log(navbar);

    menuIcon.onclick = () => {
        menuIcon.classList.toggle('bx-x');
        navbar.classList.toggle('active');
    };
}, 1000); 

Log:

<i id="menu-icon" class="bx bx-menu"></i>
<nav class="navbar"><a class="active" href="#home">Home</a><a href="#about">About</a><a href="#services">Services</a><a hre

I think if cuz the js loads first the dash app, which causes no variable to be recognized

So, what i have to do?

1 Answers1

0

You should use DOMContentLoaded event:

document.addEventListener('DOMContentLoaded', () => {
  const menuIcon = document.querySelector('#menu-icon');
  const navbar = document.querySelector('.navbar');

  console.log(menuIcon);
  console.log(navbar);

  menuIcon.onclick = () => {
    menuIcon.classList.toggle('bx-x');
    navbar.classList.toggle('active');
  };
});
FooBar
  • 1
  • 1
  • Still doesnt work: Uncaught TypeError: Cannot set properties of null (setting 'onclick') at HTMLDocument. (scripts.js?m=1682817834.418762:8:22) 127.0.0.1 - - "GET / HTTP/1.1" 200 - 127.0.0.1 - - "GET /assets/style.css?m=1682800069.545941 HTTP/1.1" 304 - 127.0.0.1 - - "GET /assets/style.scss?m=1682800069.5159411 HTTP/1.1" 304 - 127.0.0.1 - - "GET /assets/scripts.js?m=1682817834.418762 HTTP/1.1" 304 - 127.0.0.1 - - "GET /_dash-layout HTTP/1.1" 200 - 127.0.0.1 - - "GET /_dash-dependencies HTTP/1.1" 200 - then assets – Italo Buitron Apr 30 '23 at 01:26
  • it's because the element is not yet loaded when the code is read. Could you please check https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element and try solutions there. If that also does not work, let me know - we can find a solution with checking the element's existence – Aziza Kasenova May 01 '23 at 14:45