Question

http://www.devbridge.com/projects/autocomplete/jquery/

The sidebar on the left initially prints lower down the page, but when you scroll it moves up to the top and then stays instead of disappearing beyond the top of the viewport. I've seen this a lot.

Was it helpful?

Solution

You might want to take a look at the sticky.js jQuery plugin. It handles such things quite nicely if you do not need it too fancy.

The principle behind it is to check for scrolling in the container of an element. It gets fixed once it reaches a certain scroll level.

OTHER TIPS

When the scroll-top of the page is greater than the top position of the div you want to scroll, give that div a fixed position so that it follows the user down the page.

Example:

Here I've hardcoded the top position because it never changes in my usecase.

var $window = $(window), $menu = $("#menu");
$window.bind('scroll', function() {
    var pos = +$window.scrollTop();
    if (pos > 284) {
        $menu.addClass("fixed");
    }
    else {
        $menu.removeClass("fixed");
    }
}).trigger("scroll");​

where fixed is a class that sets the position to fixed and top to 0.

Using jQuery, you add an scroll-Listener to the document:

$(document).scroll(function() {

});

Inside that function you check if the scrollHeight of the document is larger than the y-position of the element:

if($(document).scrollTop() < $('.sidebar').offset().top) {
    // here you change the css attributes position to fixed and top to 0
    $('.sidebar').css('position', 'fixed').css('top', 0);
} else {
    // change the position of the element to relative (default)
    $('.sidebar').css('position', 'relative');
}

This nearly works, but because you always check the position of the fixed element, the y-position is always 0. To get it work, you just have to save the default y-position. This is the code, which I am also using:

var initial_y = $('.sidebar').offset().top;

$(document).scroll(function() {
    $e = $('.sidebar');
    if(initial_y - $(document).scrollTop() <= 0) {
        $e.css('position', 'fixed').css('top', 0);
    } else {
         $e.css('position', 'relative');
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top