lolka_bolka lolka_bolka - 5 months ago 101
jQuery Question

Bootstrap affix reset not works

I am trying to implement an affix in bootstrap. It shouldn't be a problem, but I want to make it responsive.

When a page has resized, some elements will hide at the top of the page, and because of change of width, I need to reset the affix and set to the new position.

I just search for it, and found an accepted solution, but it seems, it is not works.

This is what I've tried:

$(window).off('#myAffix');
$('#myAffix').removeData('bs.affix').removeClass('affix affix-top affix-bottom');
$('#myAffix').affix({
offset: {
top: function () {
console.log('Offset top from: ' + $('.navbar').offset().top);
return (this.top = $('.navbar').offset().top);
}
}
});


I am calling it on
document.ready
, and on
window.resize
events.

I've created a demo for it. This is the steps, how you can reproduce the problem:


  • When you open it, resize the reult window while there are 2 columns before the bordered affix, and reload the page. When you scroll down, you will see, the affix is starts to work when it need.

  • Resize the window while only the left column remains. Affix is works now also.

  • Resize the window again, while the right column appears. Now affix will trigger, when it reach the previous position, the height of the left column. That is bad.



It seems, my code is running, but has no effect on affix.

PS: Do not care about the position of the affix, I just want to fix, when / where it will be fixed.

jsFiddle here.

Answer

There is only one change you need to do for your code to work as you wish, and this is to change the $(window).off('#myAffix'); to $(window).off('.affix');

This is the new function:

$.myFunction = function() {
    $(window).off('.affix')
    $('#myAffix').removeData('bs.affix').removeClass('affix affix-top affix-bottom');
    $('#myAffix').affix({
        offset: {
            top: function() {
                console.log('Offset top from: ' + $('.navbar').offset().top);
                return (this.top = $('.navbar').offset().top);
            }
        }
    });
};