Bootstrap affix does not work when navigating back

I have used Bootstrap affix to create a fixed position div that behaves similar to the "How to Format" and "Similar Questions" div that appears when you ask a new question in Stackoverflow. It works fine when I load the page the first time, but if I scroll quite far down the page, navigate away, and then return to the page with the back button, the affixed div will sometimes be affixed in the wrong place, and sometimes the fixed positioning will break and it will simply return to its normal place in the document.

Is there something wrong with how I am implementing affix?

Document layout (#engage is the affixed div). It should not scroll over #title or #footer:

Javascript

$('#engage').affix({
    offset: {
        top: $('#donation-content').offset().top,
        bottom: function () {
            return (this.bottom = $('.footer').outerHeight(true))
        }
    }
});

CSS

#engage.affix {
    position: fixed;
    top: 0;
}

@media(max-width:767px){

   #engage.affix {
    position: static;
    }
}

You can find example code at http://www.bootply.com/pxyz1hsefA. Errors tend to happen if you scroll to the bottom of the page, click on "Go somewhere else", then click on the back button. Violent scrolling up and down will also tend to break it.

Edit: Adding an .affix-bottom class to the css with absolute positioning goes some way to fixing it. At least now when it's 'broken' the div just sticks to the bottom of its scrolling range. When I scroll back to the top, it resumes it's correct fixed position again. But it's still not what I'd call stable.

#engage.affix-bottom {
  position: absolute;
  }

Answers


I think that the problem I was experiencing was due to a mismatch between the top and bottom offset values, leading to the affix plugin not knowing what state it should be in. It may be a bug in the affix plugin or how it is applied (read more at https://github.com/twbs/bootstrap/issues/4647). It also seems to manifest differently in different browsers.

In my case I could only solve it by removing the bottom offset:

$('#engage').affix({
    offset: {
        top: $('#donation-content').offset().top
        }
});

This does mean that the fixed div can overlap the footer in some situations, which is not ideal but it is more stable. I am marking this as the accepted answer for now, because it does solve the problem, though it does leave unfortunate side-effects.


Need Your Help

how to search a treenode and return it?

c# asp.net treeview

I wrote this function but I don't know how to write the rest of it

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.