Skip to content

Instantly share code, notes, and snippets.

@thexmanxyz
Last active March 6, 2020 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thexmanxyz/69ceb3247b7ac21794c1f38e197472be to your computer and use it in GitHub Desktop.
Save thexmanxyz/69ceb3247b7ac21794c1f38e197472be to your computer and use it in GitHub Desktop.
Bootstrap 4 - Scrollspy dynamic navbar offset
var initScrollSpy = function() {
var navContainer = '#mainNav'; // your navigation container
// initial bind of scrollspy
var bindScrollSpy = function() {
$('body').scrollspy({
target: navContainer,
offset: getOffset() // determine your offset
});
}
// get your offset dynamically
var getOffset = function() {
return $(navContainer).outerHeight();
};
// update the offset but only if the container size changed
var updateOffset = function() {
var cfg = $('body').data('bs.scrollspy')._config;
if(cfg.offset != getOffset()){
cfg.offset = getOffset();
$('body').scrollspy('refresh');
}
}
bindScrollSpy(); // bind scrollspy
$(window).resize(updateOffset); // react on resize event
$(".collapse").on('shown.bs.collapse', updateOffset); // react on BS4 menu shown event (only on mobile). You might omit this line if your navigation has no change in height when opened on mobile
};
initScrollSpy(); // finally call snippet
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment