redanimalwar redanimalwar - 6 months ago 112
Javascript Question

unaffix event for Bootstrap affix?

I want to combine the affix plugin with the bootstrap navbar-fixed-top class. So far I have got it working then when I scroll past the navbar it gets fixed. But when I scroll back up I want it to go back into static state again. I have seen some code I think from older bootstrap versions and a

unaffix
event. Why is it gone? Can I create one? Or how to accomplish what I am trying here?

navbar_secondary = $( '.navbar-secondary:first' );

navbar_secondary.affix( {
offset: {
top: function () {
return (this.top = navbar_secondary.offset().top )
}
}
} );

navbar_secondary.on( 'affix.bs.affix', function () { // this is actually the wrong event for this. I want this to fire when its *not* affixed
console.log('affix');
navbar_secondary.removeClass( 'navbar-fixed-top' ).addClass( 'navbar-not-fixed' );
} );

navbar_secondary.on( 'affixed.bs.affix', function () {
console.log('affixed');
navbar_secondary.removeClass( 'navbar-not-fixed' ).addClass( 'navbar-fixed-top' );
} );

Answer

Figured it out myself. This event names are totally confusing. affixed-top.bs.affix is actually the event when it goes back to being not affixed.

navbar_secondary = $( '.navbar-secondary:first' );

navbar_secondary.affix( {
    offset: {
        top: function () {
            return (this.top = navbar_secondary.offset().top )
        }
    }
} );

navbar_secondary.on( 'affixed-top.bs.affix', function () {
    console.log('unaff');
    navbar_secondary.removeClass( 'navbar-fixed-top' ).addClass( 'navbar-not-fixed' );
} );

navbar_secondary.on( 'affix.bs.affix', function () {
    console.log('aff');
    navbar_secondary.removeClass( 'navbar-not-fixed' ).addClass( 'navbar-fixed-top' );
} );

Summary

affix.bs.affix => before fixed positioning is applied to an element
affixed.bs.affix => after fixed positioning is applied to an element
affix-top.bs.affix => before a top element returns to its original (non-fixed) position
affixed-top.bs.affix => after a top element returns to its original (non-fixed) position
affix-bottom.bs.affix => before a bottom element returns to its original (non-fixed) position
affixed-bottom.bs.affix => after a bottom element returns to its original (non-fixed) position