Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fixed sidebar until a div

Tags:

jquery

css

I'm currently using this code:

$(document).ready(function () {  
    var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0));
    $(window).scroll(function (event) {
        // what the y position of the scroll is
        var y = $(this).scrollTop();

        // whether that's below the form
        if (y >= top) {
            // if so, ad the fixed class
            $('#sidebar').addClass('fixed');
        } else {
            // otherwise remove it
            $('#sidebar').removeClass('fixed');
        }
    });
});

It sets fixed on my sidebar when I scroll down after a specific point. I want that my sidebar stops being fixed after it reaches a point, which could be 200px from the bottom of the whole page. How can I do this?

like image 518
iAndrew Avatar asked Apr 27 '26 00:04

iAndrew


1 Answers

You just need to add a few more checks and calculations in your event handler. Here's some revised code that should do what you want:

$(function() {
    var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0));
    var footTop = $('#background2').offset().top - parseFloat($('#background2').css('marginTop').replace(/auto/, 0));
    var maxY = footTop - $('#sidebar').outerHeight();
    $(window).scroll(function(evt) {
        var y = $(this).scrollTop();
        if (y > top) {
            if (y < maxY) {
                $('#sidebar').addClass('fixed').removeAttr('style');
            } else {
                $('#sidebar').removeClass('fixed').css({
                    position: 'absolute',
                    top: (maxY - top) + 'px'
                });
            }
        } else {
            $('#sidebar').removeClass('fixed');
        }
    });
});

You can see it in effect at this jsFiddle.

like image 133
rossipedia Avatar answered Apr 29 '26 19:04

rossipedia