I am trying to implement a code that moves a toolbar positioned below a header to stick to the top of the viewport while scrolling down. However, I am encountering an issue where if the content height exceeds the viewport height slightly and you try to scroll to the bottom, it bounces back up just above the end of the content with a strange visual glitch. This may be due to the 'sticky' class increasing the page's height when applied, but I'm unsure how to fix it.
Javascript/JQuery:
var enableSticky = () => {
let headerHeight = $('.toolbar').offset().top;
$(window).scroll(() => {
if ($(window).scrollTop() > headerHeight) {
$('.toolbar').addClass('sticky');
} else {
$('.toolbar').removeClass('sticky');
}
});
};
CSS:
.toolbar {
width: 100%;
height: 84px;
position: relative;
}
.toolbar.sticky {
background-color: rgba(255,255,255,0.9);;
position: fixed;
top: 0;
z-index: 5;
margin-bottom: -84px;
}
HTML:
<div id="bcmMain" style="display: block;">
<h1 id="event-title"><span class="view-table-value" data-field-name="mopId">927</span> - <span class="view-table-value" data-field-name="subject">Sample Subject</span></h1>
<div class="toolbar">
<div class="status-toolbar-group toolbar-group">
<a class="button" id="level-button">Level <span class="view-table-value" data-field-name="level">3</span></a>
</div>
<div class="toolbar-group">
<a class="button" id="status-button">Status: <span class="view-table-value" data-field-name="status">complete</span></a>
<a class="button" id="pending-button">Mark Pending</a>
</div>
<div class="edit-toolbar-group toolbar-group">
<a class="button" id="submit-changes-button">Submit Changes</a>
<a class="button" id="cancel-changes-button">Cancel Changes</a>
</div>
<div class="toolbar-group">
<a class="button" id="edit-button">Edit</a>
<a class="button" id="clone-button">Clone</a>
</div>
</div>
<div id="edit-details">
<!-- CONTENT HERE -->
</div>
</div>
I have attempted using
if ($(window).scrollTop() > headerHeight + 100)
to delay adding the sticky class until further scroll before reaching the glitch point, but this only shifts the height at which the glitch occurs.
Any suggestions on improving the code to eliminate this glitch?
EDIT: Added HTML for reference. Let me know if more details are required. Thanks!
NOTE 1: The code is embedded in a Confluence page where the Confluence page header is hidden, but not the website header or sidebar. Refer to the images linked below demonstrating a non-sticky and sticky view at varying scroll positions.
NOTE 2: Data displayed on the page is fetched from a database via API for populating fields.