Resetting / changing the offset of bootstrap affix
Asked Answered
B

2

13

How do I change the offset of Affix (Twitter Bootstrap 3) to another value?

When I tried to call the method twice like this, the second one seems to be ignored and does not have any effect:

$('#navbar-main').affix({ offset: 100});
$('#navbar-main').affix({ offset: 200}); // ---> the offset will not change to 200px

Resetting the .affix callback before calling affix the second time didn't help either:

$('#navbar-main').affix({ offset: 100});
$(window).off('.affix');
$('#navbar-main').affix({ offset: 200}); // ---> the offset will not change to 200px
Berliner answered 22/5, 2014 at 3:13 Comment(0)
B
14

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})
Berliner answered 22/5, 2014 at 3:48 Comment(1)
I fixed the issue using the next solution: https://mcmap.net/q/454331/-bootstrap-affix-dynamically-on-resizePlanter
I
39

remember, you have access to the constructor at anytime with the data method…

so if you're just trying to update a value… you can do:

$('#navbar-main').data('bs.affix').options.offset = newOffset

hope that helps <3 fat

Irresolvable answered 22/5, 2014 at 6:17 Comment(2)
Don't forget that offset is an object with a top/bottom property. I was using .options.offset = x; and not .options.offset.top = x; and my affixed div was going crazy.Soapbark
I fixed the issue using the next solution: https://mcmap.net/q/454331/-bootstrap-affix-dynamically-on-resizePlanter
B
14

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})
Berliner answered 22/5, 2014 at 3:48 Comment(1)
I fixed the issue using the next solution: https://mcmap.net/q/454331/-bootstrap-affix-dynamically-on-resizePlanter

© 2022 - 2024 — McMap. All rights reserved.