Search code examples
jquerycsssticky

Fixed div between two div elements


I try to create a fixed div element when the scroll position is between two div elements. I use this code to create the fixed element:

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

$(window).scroll(function() {  
    if ($(window).scrollTop() > sidebar) {
        $('.sidebar').addClass('fixed');
    }else{
        $('.sidebar').removeClass('fixed');
    }
});

I don't know how to remove the fixed class when the blue div reached. I tried to get the current position of the blue div and add it to the if statement: var blueDiv = $('.bottom').offset().top:

if ($(window).scrollTop() > sidebar && $(window).scrollTop() < blueDiv ){
    // add fixed class
}else{
    // remove fixed class
}

Fiddle: https://jsfiddle.net/L7p5yeet/


Solution

  • You forgot to include the height of the sidebar when you checked if the sidebar already reached the blue div:

    var sidebar = $('.sidebar').position().top;
    var blueDiv = $('.bottom').position().top - $('.sidebar').innerHeight();
    
    $(window).scroll(function() {
        var sT = $(window).scrollTop();
        if (sT > sidebar && sT < blueDiv) {
            $('.sidebar').addClass('fixed');
        }else{
            $('.sidebar').removeClass('fixed');
        }
    });