Setting CSS value limits of the window scrolling animation

You can not use animate() method with scroll function it will create conflict because scroll value will change always and jQuery can not infinite repeat same animation. Stop won’t rescue this issue either, or i cound’t manage to do it.

And i suggest to use variation in if statements.

Here is not working animate sample with animate usage.

Here is same example working with css method.

$(window).scroll(function() {
    var scrollVal = $(this).scrollTop();
    if ( scrollVal > offset.top) {
        $sidebar.css({
           'margin-top': (($window.scrollTop() - offset.top) + topPadding) + 'px'
                       //added +'px' here to prevent old internet explorer bugs
        });
    } else {
        $sidebar.css({'margin-top':'0px'});
    }
});

Note: if you want to expand your if statements with else if, don’t use else, it will create conflict too. Bealive me i am really expreienced with this issue.

UPDATE:

You can change your approuch to calculations of the limits too. I presume you want to fix the nav and your html is like this:

<div class="wrapper">
    <div class="header">header</div>
    <span id="subnav">hold this</span>
</div>​

and jQuery calculations should be like this:
Here is working jsFiddle.

$(document).ready(function() {
   $(window).scroll(function() {
       var headerH = $('.header').outerHeight(true);
      //this will calculate header's full height, with borders, margins, paddings
       console.log(headerH);
       var scrollVal = $(this).scrollTop();
        if ( scrollVal > headerH ) {
        //when scroll value reach to your selector
            $('#subnav').css({'position':'fixed','top' :'0px'});
        } else {
            $('#subnav').css({'position':'static','top':'0px'});
        }
    });
 });​

Leave a Comment