Search code examples
javascriptnavigationsingle-page-applicationprogressive-web-appsmaterialize

Uncaught TypeError: Cannot read property 'init' of undefined at HTMLAnchorElement.<anonymous>


I'm making this navigation with materialize css and configure it in 2 ways, the sidenav and topnav. On the top nav while im switching pages its fine no problem but when it is in the sidenav or the mobile navigation has one problem

the console:

the console

and this is where the console is pointing to

function sideNav() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
      if (this.readyState == 4) {
        if (this.status != 200) return;

        // Muat daftar tautan menu
        document.querySelector(".sidenav").innerHTML = xhttp.responseText;
        $(".dropdown-trigger").dropdown();
        $(".sidenav").sidenav();

        // Daftarkan event listener untuk setiap tautan menu
        document.querySelectorAll(".link2").forEach(function (elm) {
          elm.addEventListener("click", function (event) {
            // Muat konten halaman yang dipanggil
            var sidenav = document.querySelectorAll(".sidenav");
            M.Sidenav.getInstance(sidenav).init(sidenav);
            page = event.target.getAttribute("href").substr(1);
            loadPage(page);
          });
        });
      }
    };
    xhttp.open("GET", "/pages/sidenav.html", true);
    xhttp.send();
  }
  sideNav();

can you help me?


Solution

  • Check the sidenav instance, whether it is loaded on DOM as that might be the issue. Console log also the sidenav variable and see if the select query returns anything.