Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery follow scroll

I have a sort of sidebar on my website, which has to scroll down together with the user so that it is always in the view.

The code I'm using now is actually working fine however there is one problem. On smaller screens the sidebar scrolls before your at the sidebar thus making it impossible to see it all even if you scroll.

So what I want is the sidebar to scroll with the bottom instead of it being pushed down with the top so that when you reach the end of the sidebar it starts to scroll.

This is the code that I'm currently using.

var documentHeight = 0;
var topPadding = 10;
$(function() {
    var offset = $("#mainright").offset();
    documentHeight = $(document).height();
    $(window).scroll(function() {
        var sideBarHeight = $("#mainright").height();
        if ($(window).scrollTop() > offset.top) {
            var newPosition = ($(window).scrollTop() - offset.top) + topPadding;
            var maxPosition = documentHeight - (sideBarHeight);
            if (newPosition > maxPosition) {
                newPosition = maxPosition;
            }
            $("#mainright").stop().animate({
                marginTop: newPosition
            });
        } else {
            $("#mainright").stop().animate({
                marginTop: 0
            });
        };
    });
});

like image 646
MadsK Avatar asked Jul 28 '26 08:07

MadsK


1 Answers

I guess the "best practice" for accomplishing a task like this is to use dynamically changing css position from absolute to fixed and vice versa. A basic example could look like:

$(function(){
   var $box    = $('.box'),
       offset  = $box.offset(),
       doc_h   = $(document).height();

    $(window).scroll(function(){
        if($(window).scrollTop() > offset.top) {
            if(!$box.hasClass('fix'))
                $box.toggleClass('normal fix');
        }
        else{
            if(!$box.hasClass('normal'))
                $box.toggleClass('normal fix');
        }
    });
});​

Example in action: http://www.jsfiddle.net/YjC6y/14/

like image 178
jAndy Avatar answered Jul 29 '26 20:07

jAndy