Bootstrap Affix Dynamically on Resize

How to get dynamic data-offset values for Bootstrap 3 affix method

You could use jQuery to get the dynamic content height above the navbar. For example:

$('#nav').affix({
offset: {
top: $('header').height()
}
});

Working demo: http://bootply.com/69848

In some cases, offset.bottom must also be calculated to determine when to "un-affix" the element. Here's an example of affix-bottom

Resetting / changing the offset of bootstrap affix

Here's how. The key is to both call off on .affix, and also, removeData on the affix'ed element. Let's say I want to reset the affix of #navbar-main:

Bootstrap < 3 (from es128):

$(window).off('.affix')
$('#navbar-main').removeData('affix').removeClass('affix affix-top affix-bottom')
$('#navbar-main').affix({ offset: 400})

Bootstrap 3 (from Dysko):

$(window).off('.affix')
$('#navbar-main').removeData('bs.affix').removeClass('affix affix-top affix-bottom')
$('#navbar-main').affix({ offset: 400})

Changing offset dynamically in affix plugin

Had a similar situation with a new site I'm working on (slideshow above affixed navbar changes height when window resizes, leaving the affixed navbar with the wrong offset).

The answer is to delete the affix data from the jQuery data cache and then remove any classes associated with the affix plugin, like this:

$([selector]).removeData('affix').removeClass('affix affix-top affix-bottom');

I found that at the bottom of https://github.com/twbs/bootstrap/issues/5870

Bootstrap affix reset not works

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);
}
}
});
};

Resetting Boostrap Affix with new offset in responsive website

Would it work for your design if at the mobile viewport you simply used position:fixed; top:0;left:0;width:100%; for the the nav div, and then give the page content div some padding at the top so it clears the nav?



Related Topics



Leave a reply



Submit