简体   繁体   中英

Adding hover delay to drop down menu

I'm trying to add a delay to a jquery drop down menu. I've gotten the delay to work correctly. But it's adding the delay to all of the drop down menus. Here is the code I'm using:

var timer;
var delay = 1000;
$('.header__nav-main-list > li', '#header').hover(function() {
    timer = setTimeout(function(){
        $('.header__nav-main-list > li', '#header').children(".header__nav-sub-list").show();
        $('.header__nav-main-list > li', '#header').addClass("is-open");
    }, delay);
}, function() {
    clearTimeout(timer);
    $(".header__nav-sub-list").hide();
    $('.header__nav-main-list > li').removeClass("is-open");
});

Instead I want it to only add the delay to the nav item I am hovering over so I tried something like this below, but instead it can't determine what "this" is referring to.

var timer;
var delay = 1000;
$('.header__nav-main-list > li', '#header').hover(function() {
    timer = setTimeout(function(){
        $(this).children(".header__nav-sub-list").show();
        $(this).addClass("is-open");
    }, delay);
}, function() {
    clearTimeout(timer);
    $(".header__nav-sub-list").hide();
    $('.header__nav-main-list > li').removeClass("is-open");
});

Indeed you cannot use $(this), but it should work like that:

var timer;
var delay = 1000;
$('.header__nav-main-list > li', '#header').hover(function(event) {
    var $this = $(this);
    timer = setTimeout(function(){
        $this.children(".header__nav-sub-list").show();
        $this.addClass("is-open");
    }, delay);
}, function() {
    clearTimeout(timer);
    $(".header__nav-sub-list").hide(0);
    $('.header__nav-main-list > li').removeClass("is-open");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM