Вопрос

I have this situation where if hovering over a #main-nav li item it will show the subnav. But I need a delay to allow user to reach it (subnav). I've tried solutions like this but if I hover on another item, it doesn't hide the previous hovered item until delay is over. Then I tried adding if statements within handlerOut to determine if hovering over another nav item or mouseOut #main-nav section allowing the timer to run (but doesn't run since within handlerOut).

Here's the code below and here it is on jsfiddle.

var $mainlist = $('#main-nav li');
var $subnav = $('#main-nav li ul');

$(function () {

    $mainlist.hoverIntent(

    function () {
        $(this).addClass('active');
    },

    function () {
        if ($('#main-nav li').hover() && $('#main-nav li').not($(this))) {
            $(this).removeClass('active');
        } else if ($('#main-nav').add($subnav).mouseleave()) {
            timer = setTimeout(function () {
                $('#main-nav').find('li.active').removeClass('active');
            }, 1000);
        }
    });

    $subnav.hover(

    function () {
        clearTimeout(timer);
    },

    function () {
        //
    });
});

Please disregard how the sub-nav is positioned as it relates to the site styling.

Any help would be greatly appreciated.

Это было полезно?

Решение

There were a few issues with your code:

First, the selectors:

If you want the immediate children, use >:

var $mainlist = $('#main-nav > li');

You also forgot the # in the second selector.

From there, it was pretty straight-forward, assuming I got your scenario correctly:

  • When entering a main list item, I remove the active class from the previously selected item, if any.
  • When leaving the such element, create a timeout that allows you to enter the sub-menu.
  • When entering the sub-menu, clear the timeout to leave the sub-menu visible.
  • When leaving the sub-menu, deactivate it.

A working version can be found here.

Note that I colorized the sub-menu to make it clear when you're entering or leaving it.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top