0
votes

I currently have the following code on a wordpress site. The scroll function hides the cart button if scrollTop is less than the height of the navigation bar. This is so that on mobile, the cart button (fixed to top right) does not block the collapsed menu button. I wish to have this functionality disabled on windows with a width greater than 1024px, as I have tried with the window resize function.

jQuery(document).scroll(function() {
    var y = jQuery(this).scrollTop();
    if (y > jQuery('.x-navbar-inner').height()) {
        jQuery('.x-menu-item-woocommerce').fadeIn(1000);
    } else {
        jQuery('.x-menu-item-woocommerce').fadeOut(1000);
    }
});

jQuery(window).resize(function(){
    if (jQuery(window).width() >= 1024) {  
        jQuery('.x-menu-item-woocommerce').show();
    }     
});

I am unsure as to how I can get this to work. I tried wrapping the scroll function around the window resize function as shown, however this did not work.

jQuery(window).resize(function(){
    jQuery(document).scroll(function() {
    var y = jQuery(this).scrollTop();
    if (y > jQuery('.x-navbar-inner').height()) {
        jQuery('.x-menu-item-woocommerce').fadeIn(1000);
    } else {
        jQuery('.x-menu-item-woocommerce').fadeOut(1000);
    }
});


    if (jQuery(window).width() >= 1024) {  
        jQuery('.x-menu-item-woocommerce').show();
    }     
});
1

1 Answers

0
votes

You can use off() to remove the listener.

Since you may want to implement it again it is cleanest to move the code to a handler function

Wrap the scroll on/off in the resize handler, then trigger resize on page load

function scroller(){
   //your scroll stuff
}

jQuery(window).resize(function(){

       if (jQuery(window).width() >= 1024) {

              jQuery('.x-menu-item-woocommerce').show();
              jQuery(window).off('scroll');

       } else{
             jQuery(window).scroll(scroller);
       }    
// trigger event on page load
}).resize();