Created
November 13, 2017 18:27
-
-
Save sarvar/79ecdc7c97bbdc9d6debf94fc19e57cb to your computer and use it in GitHub Desktop.
Sticky Bootstrap navbar on scroll for Bootstrap 4
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
<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 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
$(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 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
.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
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.