-
-
Save shakilbd948/c08bca7a1bcad418810b5e5c5eb43dd8 to your computer and use it in GitHub Desktop.
Sticky Bootstrap navbar on scroll for Bootstrap 4
This file contains 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
<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> |
This file contains 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
$(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)); | |
}); | |
}); |
This file contains 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
.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