1

Just the first "else" not working. topColor div will expand from original 15 high to 150 high when scrolling down, but not shrink back to 15 high when I scroll near the top.

$(document).ready(function () {
    $(window).scroll(function () {
        if ($(this).scrollTop() > 20) {
            $('#topColor').animate({
                height: "150px"
            });
        } else {
            $('#topColor').animate({
                height: "15px"
            });
        }
        if ($(this).scrollTop() > 300) {
            $("#fixedMenuBar").fadeIn('slow', 'linear');
        } else {
            $("#fixedMenuBar").fadeOut('fast', 'linear');
        }
    });
});
j08691
  • 204,283
  • 31
  • 260
  • 272
Brett
  • 21
  • 3
  • what is the value of $(this).scrollTop() ? have it log into the console with console.log($(this).scrollTop()); – teewuane Feb 27 '13 at 21:29

1 Answers1

1

You should not use else in scroll responsed animations, use else if instead for being more specific and animate will create conflict because scroll value will change always and jQuery can not infinite repeat same animation.

But if you insist on animate try this:

    var scrollVal = $(this).scrollTop();

    if ( scrollVal < 20 )
      if ( $("#fixedMenuBar").is(':visible') ) {
        $("#fixedMenuBar").fadeOut('fast', 'linear');
      }
      if ( parseInt($('#topColor').css('height')) != 150 ) {
        $('#topColor').animate({ height: "150px" });
      }

    }else if ( scrollVal >= 20 && scrollVal < 300 ) {
      if ( $("#fixedMenuBar").is(':visible') ) {
        $("#fixedMenuBar").fadeOut('fast', 'linear');
      }
      if ( parseInt($('#topColor').css('height')) != 15 ) {
        $('#topColor').animate({ height: "15px" });
      }

    }else if ( scrollVal >= 300 ) {
       if ( !$("#fixedMenuBar").is(':visible') )
        $("#fixedMenuBar").fadeIn('slow', 'linear');
    }

This answer also should help you: Setting CSS value limits of the window scrolling animation

Community
  • 1
  • 1
Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
  • +1 and you should also check if the element `$().is(':animated')` to prevent a large animation query – HenningCash Feb 27 '13 at 21:42
  • Thank you...my first jquery attempt. I added your code...but now my site doesn't load. Wrapped it in $(document).ready(function () and $(window).scroll(function (). – Brett Feb 27 '13 at 22:58
  • I ended up just using .scrollTop with translateY to slide the object down and back. Easier for now. Thanks again for your time! – Brett Feb 28 '13 at 01:06