Skip to content

Instantly share code, notes, and snippets.

@shakilbd948
Forked from sarvar/index.html
Created April 25, 2019 06:51
Show Gist options
  • Save shakilbd948/c08bca7a1bcad418810b5e5c5eb43dd8 to your computer and use it in GitHub Desktop.
Save shakilbd948/c08bca7a1bcad418810b5e5c5eb43dd8 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%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment