0

I have a menu with submenu items that fly out on hover and/or click. Everything works the first time you load a page but if you visit another site/page and come back the fly out doesn't execute. (All of the other scripts on the page work fine.) I get these error messages and it looks like it just doesn't think the menu.htm file has loaded.

jquery-3.6.0.min.js:2 jQuery.Deferred exception: Cannot read property 'addEventListener' of null TypeError: Cannot read property 'addEventListener' of null... jquery-3.6.0.min.js:2 Uncaught TypeError: Cannot read property 'addEventListener' of null at menu.js:29..

menu.js is in bundle.js which is way over my head to modify. How would I force menu.htm to reload every time or make menu.js recognize the cache?

<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <header class="page-header inverse">
    <div class="page-header__inner">
      <div id="menu" class="container"></div>
    </div>
  </header>
  <script>
  $("#menu").load("menu.htm");
  </script>

<main>Content</main>

  <script src="js/vendors.js"></script>
  <script src="js/bundle.js"></script>
</body>
Nevada DMV
  • 31
  • 2
  • Does this answer your question? [Cannot read property 'addEventListener' of null](https://stackoverflow.com/questions/26107125/cannot-read-property-addeventlistener-of-null) – AaronJ Aug 19 '21 at 18:26
  • $( document ).ready() is needed before any jquery or it might go too fast –  Aug 19 '21 at 18:31
  • all jquery code must be called inside it or accessed from it to make sure the document is ready –  Aug 19 '21 at 18:31
  • "'addEventListener' of null" means that the variable that the property addEventListener is used on is not defined (yet) -- you can not call addEventListener on null. Either the variable has not been defined OR the element that the variable should refer to has not been created. SO like @SolomonPByer suggest make sure that the DOM is fully loaded before adding event listeners etc. – chrwahl Aug 19 '21 at 18:36
  • I'm using JQuery to load the menu so waiting for a Document Ready doesn't make too much sense. It looks like bundle.js is executing before the menu is loaded, so I tried defer on bundle.js. That didn't fix it. I tried Document Ready to load bundle.js and that didn't work either; – Nevada DMV Aug 19 '21 at 19:50
  • $(document).ready(function(){ $.getScript("js/bundle.js", function(){}); }); Am I doing this right? – Nevada DMV Aug 19 '21 at 19:51
  • $(document).ready(()=>{$("#menu").load("menu.htm");}) should work –  Aug 19 '21 at 23:02
  • $(document).ready(()=>{$("#menu").load("menu.htm");}) broke it completely. bundle.js has to run after the menu loads. What did work was putting $(document).ready(function(){ $.getScript("js/bundle.js", function(){}); }); inside the menu.htm file at the end. So, by definition, all of the menu content has to be there before it runs. Maybe I'm just a hack but it works. – Nevada DMV Aug 20 '21 at 00:03

0 Answers0