jorenwouters
jorenwouters

Reputation: 105

Make div unfixed after scroll

With the following code, I made my div fixed after you scroll to that div. But, no my sidebar is scrolling with me, which is fine. But I want it to stop, because otherwise it is overlapping the footer. How do I do this?

I used the following code:

var fixmeTop = $('.whitepaper-section').offset().top;
var footer = $('#footer_bg').offset().top;

if ($(window).width() > 1035) {
    $(window).scroll(function() {
        var currentScroll = $(window).scrollTop();
        if (currentScroll >= fixmeTop && currentScroll <= footer) {
            $('.whitepaper-section').addClass('fixed');
        } else {
            $('.whitepaper-section').removeClass('fixed');
        }
    });
}

The website is https://cashcontroller.nl/nieuws/

Regards, Joren

Upvotes: 0

Views: 265

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

You were close.

The thing is that currentScroll never can be higher than your footer position.

currentScroll is the amount of pixels above the viewport. So the "reference" for elements position to pass is the viewport's top. That never happens to your footer, obviously.

So! You have to add the .whitepaper-section height to currentScroll and compare with the footer's position.

Additionnally, .whitepaper-section is fixed with a top position... You have to add this distance too. I estimated it to 1em in the code below.

var fixme = $('.whitepaper-section');
var fixmeTop = fixme.offset().top;
var fixmeHeight = fixme.outerHeight();
var fixedtopOffset = 1em;   // Adjust that with the value you have in CSS .fixed
var footer = $('#footer_bg').offset().top;

if ($(window).width() > 1035) {
    $(window).scroll(function() {
        var currentScroll = $(window).scrollTop();
        if (currentScroll >= fixmeTop && currentScroll + fixmeHeight + fixedtopOffset <= footer) {
            $('.whitepaper-section').addClass('fixed');
        } else {
            $('.whitepaper-section').removeClass('fixed');
        }
    });
}

Upvotes: 1

Related Questions