JSFiddle - React, Tailwind, and code Playground
HTML
<div id="top" style="width: 100%; height: 100px; background: #ccc; margin: 0;">Top Panel</div>
<div id="mainMenuBar" style="width: 100%; height: 30px; background: #999; margin: 0;">Sticky Panel</div>
<div id="content" style="width: 100%; height: 3000px; background: #ccc; margin: 0;">
Content Panel
<br/>
<br/>
This panel will not jump when the sticky panel becomes stuck.
</div>
<div id="footer">footer</div>
CSS
.stick {
position: fixed;
top: 0;
}
#footer { height:900px; }
JavaScript
$(document).ready(function() {
// Cache selectors for faster performance.
var $window = $(window),
$mainMenuBar = $('#mainMenuBar'),
$menuBarOffset = $mainMenuBar.offset().top,
window_top = 0,
footer_offset = $("#footer").offset().top,
content = $("#content"),
panel_height = $mainMenuBar.outerHeight()+'px';
// Run this on scroll events.
$window.scroll(function() {
window_top = $window.scrollTop();
if (window_top >= $menuBarOffset) {
if (window_top >= footer_offset) {
// Unstick the div.
$mainMenuBar.removeClass('stick');
content.css('margin-top', 0);
} else {
// Make the div sticky.
$mainMenuBar.addClass('stick');
content.css('margin-top', panel_height);
}
}
else {
// Unstick the div.
$mainMenuBar.removeClass('stick');
content.css('margin-top', 0);
}
});
});