Teezii Teezii - 4 months ago 14
jQuery Question

Mouseover function and mouseleave function keeps working when resize window

I want to show a menu when hover over a user. But I want the hover gone when the window size is below 977.

Here is my code:

$(document).ready(function() {
$(window).on("load resize", function(event){
var windowSize = $(window).width();
var timer;
if (windowSize >= 977) {
$(".crmUser, .userMenu").on("mouseover", function() {
clearTimeout(timer);
openSubmenu();
}).on("mouseleave", function() {
timer = setTimeout(
closeSubmenu
, 800);
});

function openSubmenu() {
$(".userMenu").addClass("userOpen").fadeIn("fast");
}
function closeSubmenu() {
$(".userMenu").removeClass("userOpen").fadeOut("fast");
}
} else {
}
}).trigger("resize");
});


I even made a fiddle, but window resizing doesnt work there.
I am not sure what I am missing..

Answer

Use :

$(document).width();

Instead of :

$(window).width();

And use the condition $(document).width()>=977 inside event's callback (mousehover) :

   $(".crmUser, .userMenu").on("mouseover", function() {
        if($(document).width()>=977){
            clearTimeout(timer);
            openSubmenu();
        }

    })
Comments