lifejuggler
lifejuggler

Reputation: 460

sticky sidebar creating infinite scrolling

I have used almost exact coding as the http://css-tricks.com/scrollfollow-sidebar/ which does not have infinite sidebar but mine does.

Code:

$(function() {  
    var $sidebar   = $("#left_column"), 
        $window    = $(window),
        offset     = $sidebar.offset(),
        topPadding = 50;
    $window.scroll(function() {
    //console.log($('.view-content').height());
    //@todo, check content height to prevent "infinite scrolling";  this occurs when the sidebar is not fully displayed on the page
        if ($window.scrollTop() > offset.top) {
            $sidebar.stop().animate({
                marginTop: $window.scrollTop() - offset.top + topPadding
            });
        } else {
            $sidebar.stop().animate({
                marginTop: 0
            });
        }
    });    
});

css:

#left_column {
float: left;
top: -10px;
    position: relative;
width: 200px;   

}

But this code makes infinite scrolling where every time i near the end, it pushes down the side bar by 30-50% of the window total height what am i doing wrong?

Upvotes: 0

Views: 1722

Answers (1)

mfchris
mfchris

Reputation: 11

i had already the same problem and i think i found a possible solution and i will demonstrate it within your code sample:

$(function() {  
var $sidebar   = $("#left_column"), 
    $window    = $(window),
    offset     = $sidebar.offset(),
    topPadding = 50;

$window.scroll(function() {
//console.log($('.view-content').height());
//@todo, check content height to prevent "infinite scrolling";  this occurs when the sidebar is not fully displayed on the page
var  docHeight = $(document).height()-700;
  if($(window).scrollTop() < docHeight) {
    if ($window.scrollTop() > offset.top) {
        $sidebar.stop().animate({
            marginTop: $window.scrollTop() - offset.top + topPadding
        });
    } else {
        $sidebar.stop().animate({
            marginTop: 0
        });
    }
 }
});    
});

You have to add a variable called docHeight containing the documentHeight substracted an average height of a window (e.g. 700) and then set a new if-clause in the scroll-function to prevent scrolling within the defined height-level near to the bottom of the document.

Upvotes: 1

Related Questions