1

I'm trying to create fixed-top menu, and resize them (by changing padding top&bottom) when window scrolled down > 300px for example. If i try that after 300px from top, set css style like $('nav').css('padding', '30px 0 30px 0'); all work fine, but if i try to do this with animation, i get huge latency between events.

There is example: Without animate - http://jsfiddle.net/g3xLgLeb/1/ (all work fine)

With animate - http://jsfiddle.net/g3xLgLeb/ (huge latency)

kxc
  • 1,357
  • 2
  • 16
  • 39
  • every time you scroll you call an animation: you should check before if `$nav.is(':animated');` before starting a new animation – Fabrizio Calderan Sep 04 '14 at 11:11
  • Hope this post helps you to achieve your [goal](http://stackoverflow.com/questions/16442016/jquery-sticky-header-that-shrinks-when-scrolling-down) – Benjamin Sep 04 '14 at 11:17

1 Answers1

1

I would prefer to use CSS transition rather than jQuery animation for this.

Here's how you can do it.

Add the following css to your existing css file:

.nav.custom{
  padding-top:5px;
  padding-bottom: 5px;
  -webkit-transition: all ease 0.5s;
  -moz-transition: all ease 0.5s;
  -ms-transition: all ease 0.5s;
  transition: all ease 0.5s;
}

Use the following as your script:

   $(document).ready(function() {
        var $nav = $('.nav');
        $(window).scroll(function () {
            if ($(this).scrollTop() > 350) {
                $nav.addClass('custom');
            } else {
                $nav.removeClass('custom');
            }
        });
    });

NOTE: The css transitions may not work in some older browsers. Here's a list showing the cross browser compatibility.

Hope this helps. :)

Rishabh Shah
  • 679
  • 7
  • 20
  • @Benjamin, I don't think it will work that way. Because `toggleClass` will be then called only if `scrollTop() > 350`. So when will it add the class and when will it remove? – Rishabh Shah Sep 04 '14 at 11:26
  • @kxc It helps but beware you will get cross browser compatibility issues. – Benjamin Sep 04 '14 at 11:39
  • @kxc check this [link](http://caniuse.com/#feat=css-transitions) for more details – Benjamin Sep 04 '14 at 11:40