I have site where I want 'sub navigation'. So when you scroll to section, its tool bar will affix below the main toolbar. I have this working, but I can't change the top offset after initailization. The docs say:
affix('refresh')
When using affix in conjunction with adding or removing of elements from the DOM, you'll want to call the refresh method:
but when I try this I get:
Uncaught TypeError: Object # has no method 'refresh'
Here is my code:
$(function () {
$('.sec-nav').addClass("affix-top");
var adjustNavs = function (first) {
$('.sec-nav').each(function (){
var $p = $(this).closest('.sec');
var $$ = $p.prevAll('.sec');
console.log($$);
var h = 0;
$$.each(function () { h+=$(this).outerHeight();});
console.log(h);
if (first) {
$(this).affix({offset: {top: h}});
} else {
$(this).data('affix', {b: {options: {offset:{top: h}}}});
console.log(this);
$(this).affix('refresh')
}
});
}
adjustNavs(true);
$('.sec').bind('DOMSubtreeModified', function () {
adjustNavs();
});
});
I've tried different variation of
$(this).data('affix', {b: {options: {offset:{top: h}}}});
including:
$(this).affix({offset: {top: h}});
I cannot get the offset to change. How do you change the offset of the affix plugin? Thanks.
I figured it out. Instead of dynamically updating the offset, I changed the offset value to a function:
$(function () {
$('.sec-nav').addClass("affix-top").each(function (){
var $self = $(this);
var offsetFn = function () {
var $p = $self.closest('.sec');
var $$ = $p.prevAll('.sec');
var h = 0;
$$.each(function () { h+=$(this).outerHeight();});
return h;
}
$self.affix({offset: {top: offsetFn}});
});
});
Now when a section changes due to dom manipulation or window re-size, the offset is automaticly changed due to the functions return value changing.
I simplified Fatmuemoo's answer slightly for a more basic case: My home page's nav bar (the default bootstrap #masthead) sits below a big background slider with id #bg. The height of the slider varies with 3 css breakpoints. We just set the offset of the #masthead to equal the height of the slider. Easy!
$('header#masthead').affix({ //sticky header at bottom of bg
offset: {
top: function(){return $("#bg").outerHeight();}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With