jeudi 29 juillet 2021

setTimeout doesn't work on first time in dropdown menu

i wanted to add a hover delay on dropdown menu link, that after a 1sec it opens another dropdown with another links, it adds a class with display:block on hover. My js code works fine, except! it won't display another submenu on the first time.

Scenario:

  1. Entering the page
  2. Hover on menu to see submenu
  3. Hover on submenu link to see another submenu, it should show after a 1 second
  4. It doesn't show
  5. Repeat point 3. and it actually works.
 const flyoutSubEl = this.el.querySelector(`[${this.options.megaMenuSubId}='${flyoutSubId}']`);
        const flyoutSubTriggerEl = this.el.querySelector(`[${this.options.megaMenuSubTrigger}='${flyoutSubId}']`);

        if (flyoutSubEl.classList.contains(this.options.menuActive)) {
            if (this.eventTrigger == 'click') {
                this._closeAllFlyoutsSub();
            }
        } else {
            let timer;
            flyoutSubTriggerEl.addEventListener("mouseenter",()=>{
                timer = setTimeout(()=>{
                    this._closeAllFlyoutsSub(this.options.menuActive);
                    flyoutSubEl.classList.add(this.options.menuActive);
                }, 500);
            })
            flyoutSubTriggerEl.addEventListener("mouseleave",()=>{
                clearTimeout(timer);
            })
            
        }

Does anyone have a clue about why is this code not working on the first time? Console isn't showing anything usefull, if the dropdown should be on display:block from the beggining, then why is this working on second time?

Thanks for help!




Aucun commentaire:

Enregistrer un commentaire