Last active
June 23, 2020 16:11
-
-
Save brankoconjic/54b85e8efcee6a97fb7831803f10903f to your computer and use it in GitHub Desktop.
Adds sticky header functionality to Sinatra theme.
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 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