0

this is a function to open a sub menu in a navbar, it works on desktop but on mobile it doesnt

const mostrarHijos = () => {
  for (let i = 0; i < subMenu.length; i++) {

    if (window.innerWidth < 992) {
      let subMenuItem = document.querySelectorAll(".sub-menu")[i];
      let hijos = document.querySelectorAll(".children")[i];

      subMenuItem.addEventListener("click", () => {
        hijos.classList.toggle("children-expand");
        hijos.classList.toggle("children-retread");
      });
    }
    if (window.innerWidth >= 992) {
      let subMenuItem = document.querySelectorAll(".sub-menu")[i];
      let hijos = document.querySelectorAll(".children")[i];

      subMenuItem.addEventListener("mouseover", () => {
        hijos.classList.add("children-expand");
        hijos.classList.remove("children-retread");
      });

      subMenuItem.addEventListener("mouseleave", () => {
        hijos.classList.remove("children-expand");
        hijos.classList.add("children-retread");
      });
    }
  }

  if (window.innerWidth >= 992) {
    menuRes.classList.remove("expand");
    menuRes.classList.remove("hide");
  }
};
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    Why don't you simply use css mediaQueries, they are spécificaly made for this kind of problem, and work on any device... (even if js interpretor are locked) – Mister Jojo Apr 11 '23 at 17:42
  • 3
    One really bad things about your code is you keep looling up the elements over and over again. `let subMenuItem = document.querySelectorAll(".sub-menu")[i];` Do it once and use the index. – epascarello Apr 11 '23 at 17:44
  • 1
    This code should not even exist. Learn CSS `:hover`. Also mobile devices generally have no mouse events. – Kosh Apr 11 '23 at 17:52
  • 1
    There's nothing technically wrong with the code. This is an eslint warning because its programmer considers this kind of coding to be confusing. If you wish to use it, disable that lint warning. – Barmar Apr 11 '23 at 17:54
  • 1
    The problem was worse before ES6 because variables declared with `var` didn't work as expected in code like this. See https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Barmar Apr 11 '23 at 17:57

0 Answers0