Fixed div between two div elements

Viewed 2445

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/

2 Answers
Related