Setting CSS value limits of the window scrolling animation

I have a <div id='map'> map that slides as the user scrolls down. However, it seems to let the map scroll forever, never letting the user actually reach the bottom of the page (there is a footer).

What I am trying to do is get the <div> to stop scrolling when it reaches the end of another dynamically-sized (height is variable) <div>. These two <div>s are side-by-side and in the same row.

Here is the JavaScript code I'm using to make the right div move with the user's scroll:

$(function() {

    var $sidebar   = $("#map"),
        $window    = $(window),
        offset     = $sidebar.offset(),
        topPadding = 15;

    $window.scroll(function() {
        if ($window.scrollTop() > offset.top) {
            $sidebar.stop().animate({
                marginTop: $window.scrollTop() - offset.top + topPadding
            });
        }
        else {
            $sidebar.stop().animate({
                marginTop: 0
            });
        }
    });
});

Solution 1:

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'});
        }
    });
 });​