Last active
March 6, 2020 09:26
-
-
Save thexmanxyz/69ceb3247b7ac21794c1f38e197472be to your computer and use it in GitHub Desktop.
Bootstrap 4 - Scrollspy dynamic navbar offset
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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