Sanjeev K Sanjeev K - 5 months ago 16
Javascript Question

Menu overlapping/floating while after scroll

I have a issue on this website can be checked here http://mynahcare.com, actually I have a mega menu that is working fine but when you scroll up/down page at once and then mouseout the search box moving back to header,

Code for this is following

$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 115) {
$("#master-search-flex").addClass("msearch-fixed");
$(".main-nav > li:nth-child(2) > a, .main-nav > li:nth-child(3) > a, .sub-menu-block, .location").mouseenter(function() {
$("#master-search-flex").removeClass("msearch-fixed");
});
$(".main-nav > li:nth-child(2) > a, .main-nav > li:nth-child(3) > a, .sub-menu-block, .location-inner").mouseleave(function() {
$("#master-search-flex").addClass("msearch-fixed");
});
$(".nav-secondary > li:nth-child(2), .nav-secondary > li:nth-child(4)").mouseenter(function() {
$("#master-search-flex").addClass("msearch-fixed");
});
} else {
$("#master-search-flex").removeClass("msearch-fixed");
}
});

Answer

I go thru the URL provided by you. Actually u write some code within if condition. You forget if we assign a function to any Dom element that working always. Your function run in both condition for that you face trouble. You should use unbind() for prevent unwanted action in wrong condition part.

For you code paste below.

$(window).scroll(function() 
        {    
            var scroll = $(window).scrollTop();
            if (scroll >= 115) 
            {
                $("#master-search-flex").addClass("msearch-fixed");     
                //remove overlay issue on 2nd and 3rd menu hover
                $(".main-nav > li:nth-child(2) > a, .main-nav > li:nth-child(3) > a, .location").mouseenter(function(){
                    $("#master-search-flex").removeClass("msearch-fixed");
            });     
            $(".main-nav > li:nth-child(2) > a, .main-nav > li:nth-child(3) > a, .sub-menu-block").mouseleave(function(){
                $("#master-search-flex").addClass("msearch-fixed");
            });
            $(".nav-secondary > li:nth-child(3), .nav-secondary > li:nth-child(5), .container-fluid").mouseenter(function(){
                $("#master-search-flex").addClass("msearch-fixed");
            }); 

        } else {
            $("#master-search-flex").removeClass("msearch-fixed");
            $(".main-nav > li:nth-child(2) > a, .main-nav > li:nth-child(3) > a, .sub-menu-block, .location").unbind('mouseenter');
            $(".main-nav > li:nth-child(2) > a, .main-nav > li:nth-child(3) > a, .sub-menu-block, .location-inner").unbind('mouseleave');
            $(".nav-secondary > li:nth-child(3), .nav-secondary > li:nth-child(5), .container-fluid").unbind('mouseenter');
        }
    });
Comments