OJFord
OJFord

Reputation: 11130

Sidebar scroll x amount, then fix beneath (also fixed) header?

I'm trying to implement a fixed nav at the top, after header which is scrolled past (that much works fine at the moment) and a sidebar that scrolls down with the page, until between the first and second div elements in the sidebar, then fixes.

[EDIT: Here's the fiddle - jsfiddle.net/rqHCx/5]

I tried to modify my working code for the nav bar, not worrying about scrolling past the first element for now:

$(function() {
    var side_offset_top = $('#side').offset().top;
    var side = function(){
        var scroll_top = $(window).scrollTop();
        if (scroll_top > side_offset_top) { 
            $('#side').css({ 'position': 'fixed', 'top': 40, 'right': 0 });
        } else {
            $('#side').css({ 'position': 'relative' });
        }   
    };
    side();
    $(window).scroll(function() {
        side();
    });
});

But with this, the sidebar of course jumps right to the right side of browser - but I do not want to specify a pixel value for 'right': px as then it will screw up with different screen widths.

How can I make it just not move horizontally, and be fixed in place vertically after scrolling to it?

Also, when I scroll back up, there's a 40px margin-top introduced, I assume I need to check for a return somehow, and remove that then?

Thanks,

Upvotes: 0

Views: 1361

Answers (2)

OJFord
OJFord

Reputation: 11130

I finally got it.

$(function() {
    var ad_offset_right = $('#side-wrap').offset().right;
    var ad = function(){
        var scroll_top = $(window).scrollTop();
        if (scroll_top > 490) { 
            $('.ad300x600').css({'position':'fixed', 'top':40, 'right':ad_offset_right});
        } else {
            $('.ad300x600').css({'position':'relative'});
        }   
    };
    ad();
    $(window).scroll(function() {
        ad();
    });
});

Where 490px is the distance to the .ad300x600 class I want to fix, and 40px is the height of the nav bar fixed above the side bar.

Upvotes: 0

Adam
Adam

Reputation: 2225

If you calculate its horizontal position when it is relative (in its correct horizontal position), you can use that number to when it is fixed. I added a top and right value for when it should go back to relative to reset its position.

$(function() {
    var side_offset = $('#side').offset();
    var side_offset_top = side_offset.top;
    var side_offset_right = side_offset.right;
    var side = function(){
        var scroll_top = $(window).scrollTop();
        if (scroll_top > side_offset_top) { 
            $('#side').css({ 'position': 'fixed', 'top': 40, 'right': side_offset_right });
        } else {
            $('#side').css({ 'position': 'relative', 'top': 0, 'right': 0});
        }   
    };
    side();
    $(window).scroll(function() {
        side();
    });
});

Upvotes: 1

Related Questions