AlexM
AlexM

Reputation: 479

Bootstrap navigation bar affix property not accurate after window resize

I'm having a problem which involves the affix property in Bootstrap. Using the jQuery below it functions completely fine as far as sticking to the top of the page after scrolling down (as intended). The problem only occurs after the page has loaded and then the window is resized VERTICALLY. At this point the navigation bar no longer "sticks" to the top at the correct point while scrolling. SEE DEMO SITE HERE.

Essentially the problem seems to be that the height at which the navigation bar becomes affixed is assigned after window load, and if the page is vertically resized after that then the height at which it should begin "sticking" to the top of the page SHOULD change, but doesn't. Nothing too complicated in the JS here:

//"sticky" nav bar
    $('#navbar').affix({
        offset: {
            top: $(window).height()
        }
    });
    $('#navbar').on('affix.bs.affix', function () {
        var navHeight = $('#navbar').outerHeight(true);
        $('#body').css('margin-top', navHeight);
    });
    $('#navbar').on('affix-top.bs.affix', function () {
        $('#body').css('margin-top', 0);
    });

I basically just need a way to have the point at which it "sticks" change after resize but I can't seem to get $(window).resize working effectively with it. Any thoughts?

Upvotes: 1

Views: 1012

Answers (1)

mattybaer
mattybaer

Reputation: 21

I think what you are trying to accomplish is having the offset of your navbar updated dynamically on window.resize. If that is true than this will accomplish that.

You have the ability to update any of the properties of the affix plugin after it is intialized.

$(window).resize(function(){
    $('#navbar').data('bs.affix').options.offset = $('#navbar').offset().top;
});

Upvotes: 2

Related Questions