Search code examples
javascriptjqueryscrollwidthelement

How to hide logo at different scroll point depending on screen width


Trying to hide the logo on a sticky nav when it scrolls to 72 pixels, but on smaller screens it needs to hide when it gets to 150 pixels.

I tried to just hide it at 72 pixels but on the smaller screens it starts flashing because the element being hidden causes the scroll point to change and so it shows again, going into a loop.

jQuery(document).ready(function() {
  if ($(window).width() <= 992){    
    jQuery(window).scroll(function() {
      if (jQuery(this).scrollTop() > 150) {
        jQuery('.fl-page-header-logo').fadeOut(500);
      } else {
        jQuery('.fl-page-header-logo').fadeIn(500);
      }
  } else {
    jQuery(window).scroll(function() {
      if (jQuery(this).scrollTop() > 72) {
        jQuery('.fl-page-header-logo').fadeOut(500);
      } else {
        jQuery('.fl-page-header-logo').fadeIn(500);
      }
  });
});

Solution

  • You're not closing the jquery scrolling function. Its missing });

    jQuery(window).scroll(function() {
          if (jQuery(this).scrollTop() > 150) {
            jQuery('.fl-page-header-logo').fadeOut(500);
          } else {
            jQuery('.fl-page-header-logo').fadeIn(500);
          }
    });
    

    Can't really tell why it wouldn't work otherwise. Anyways, try this. It worked for me and it's cleaner :

    var windowsWidth = $(window).width();
    
    if (windowsWidth <= 992){ 
        fadeOutLogo(72);
    } else {
        fadeOutLogo(150);
    }
    
    function fadeOutLogo(offset){
      jQuery(window).scroll(function() {
        if (jQuery(this).scrollTop() > offset) {
          jQuery('.fl-page-header-logo').fadeOut(500);
        } else {
          jQuery('.fl-page-header-logo').fadeIn(500);
        }
      });
    }