Skip to content

Instantly share code, notes, and snippets.

@brankoconjic
Last active June 23, 2020 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brankoconjic/54b85e8efcee6a97fb7831803f10903f to your computer and use it in GitHub Desktop.
Save brankoconjic/54b85e8efcee6a97fb7831803f10903f to your computer and use it in GitHub Desktop.
Adds sticky header functionality to Sinatra theme.
/*****************************************/
/* Sticky Header JS
/*****************************************/
( function() {
var sinatraStickyHeader = () => {
var header = document.getElementById('sinatra-header');
var headerInner = document.getElementById('sinatra-header-inner');
var wpadminbar = document.getElementById('wpadminbar');
var stickyPosition = header.getBoundingClientRect().top;
var sticky = (stickyPosition - tolerance) <= 0;
var tolerance;
if ( null === wpadminbar ) {
tolerance = 0;
} else if ( window.outerWidth <= 600 ) {
tolerance = 0;
} else {
tolerance = wpadminbar.getBoundingClientRect().height;
}
var stickyPlaceholder = null;
var checkPosition = function() {
if ( null === wpadminbar ) {
tolerance = 0;
} else if ( window.outerWidth <= 600 ) {
tolerance = 0;
} else {
tolerance = wpadminbar.getBoundingClientRect().height;
}
stickyPosition = header.getBoundingClientRect().top;
sticky = (stickyPosition - tolerance) <= 0;
maybeStickHeader();
};
var maybeStickHeader = function() {
if ( sticky ) {
if ( ! document.body.classList.contains('si-sticky-header') ) {
stickyPlaceholder = document.createElement( 'div' );
stickyPlaceholder.setAttribute('id', 'si-sticky-placeholder');
stickyPlaceholder.style.height = headerInner.getBoundingClientRect().height + 'px';
header.appendChild( stickyPlaceholder );
document.body.classList.add('si-sticky-header');
}
} else {
if ( document.body.classList.contains('si-sticky-header') ) {
document.body.classList.remove('si-sticky-header');
document.getElementById('si-sticky-placeholder').remove();
}
}
};
// Initial check.
maybeStickHeader();
// Debounce scroll.
window.addEventListener('scroll', function() {
checkPosition();
});
// Debounce resize.
window.addEventListener('resize', function() {
checkPosition();
});
};
sinatraStickyHeader();
} )();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment