Skip to content

Instantly share code, notes, and snippets.

@sarvar
Created November 13, 2017 18:27
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save sarvar/79ecdc7c97bbdc9d6debf94fc19e57cb to your computer and use it in GitHub Desktop.
Save sarvar/79ecdc7c97bbdc9d6debf94fc19e57cb to your computer and use it in GitHub Desktop.
Sticky Bootstrap navbar on scroll for Bootstrap 4
<nav class="navbar" data-toggle="sticky-onscroll">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="http://bootbites.com">BootBites.com</a>
</div>
</div>
</nav>
$(document).ready(function() {
// Custom
var stickyToggle = function(sticky, stickyWrapper, scrollElement) {
var stickyHeight = sticky.outerHeight();
var stickyTop = stickyWrapper.offset().top;
if (scrollElement.scrollTop() >= stickyTop){
stickyWrapper.height(stickyHeight);
sticky.addClass("is-sticky");
}
else{
sticky.removeClass("is-sticky");
stickyWrapper.height('auto');
}
};
// Find all data-toggle="sticky-onscroll" elements
$('[data-toggle="sticky-onscroll"]').each(function() {
var sticky = $(this);
var stickyWrapper = $('<div>').addClass('sticky-wrapper'); // insert hidden element to maintain actual top offset on page
sticky.before(stickyWrapper);
sticky.addClass('sticky');
// Scroll & resize events
$(window).on('scroll.sticky-onscroll resize.sticky-onscroll', function() {
stickyToggle(sticky, stickyWrapper, $(this));
});
// On page load
stickyToggle(sticky, stickyWrapper, $(window));
});
});
.sticky.is-sticky {
position: fixed;
left: 0;
right: 0;
top: 0;
z-index: 1000;
width: 100%;
}
Copy link

ghost commented Jul 11, 2019

Good work!

@Elijha
Copy link

Elijha commented Feb 25, 2020

Line 6 should be simply > in the comparison otherwise the action sticky.removeClass("is-sticky"); is never called on desktop when you scroll back to the top at 0 units offset (do any browsers hit a negative scroll?)

I needed the class removed because I was using CSS styling to scale the Brand element smaller on scroll via a transition effect. and wanted ti restored when back to the top of the page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment