w.rabil
w.rabil

Reputation: 23

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");
});

Upvotes: 1

Views: 2202

Answers (1)

yezzz
yezzz

Reputation: 3020

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");
});

Upvotes: 4

Related Questions