Keith Keith - 3 months ago 17
CSS Question

Window resize doesn't work

I have a menu that on hover above 990px it opens the menu but when its below, the menu turns into a hamburger menu and you need to open it. The problem is I want to disable the hover when below 990px. This only works when the window is opened below 990px. If it starts above 990px and is reduced to below 990px, the window keeps the hover state on since the window opened above the 990px mark. I tried to add a resize() to it, but it doesn't seem to work.

jQuery(function($) {
if ($(window).width() >= 992) {
$('.navbar .dropdown').hover(function () {
$(this).find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
}, function () {
$(this).find('.dropdown-menu').first().stop(true, true).delay(100).slideUp();
});
}else if ($(window).width <= 992) {
$('.navbar .dropdown').off('mouseenter');
}
});


Now when the window resizes, it disables the hover completely no matter what.

Answer

This is what I came up with and it works for future reference:

jQuery(function ($) {
    if ($(window).width() > 992) {
        $('.navbar .dropdown').hover(function (e) {
            $(this).find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();

        }, function () {
            $(this).find('.dropdown-menu').first().stop(true, true).delay(100).slideUp();

        });

        $('.navbar .dropdown > a').click(function () {
            location.href = this.href;
        });
    }

$(window).resize(function () {
    var win = $(window).width();
    if (win >= 992) {
        $('.navbar .dropdown').hover(function () {
            $(this).find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
        }, function () {
            $(this).find('.dropdown-menu').first().stop(true, true).delay(100).slideUp();
        });
        // this takes off the hover event if using on desktop
    } else if (win < 992) { $('.navbar .dropdown').off('mouseenter'); }
});

});