Created
May 6, 2016 17:37
-
-
Save mikeoberdick/0699e1631abd1a7196fe6a8746a8e5db to your computer and use it in GitHub Desktop.
Creates a jQuery sticky header on scroll
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
<script> | |
// Create a clone of the menu, right next to original | |
$('.site-header').addClass('original').clone().insertAfter('.site-header').addClass('cloned').css('position','fixed').css('top','0').css('margin-top','0').css('z-index','500').removeClass('original').hide(); | |
scrollIntervalID = setInterval(stickIt, 10); | |
function stickIt() { | |
var orgElementPos = $('.original').offset(); | |
orgElementTop = orgElementPos.top; | |
if ($(window).scrollTop() >= (orgElementTop) ) { | |
// scrolled past the original position; now only show the cloned, sticky element. | |
// Cloned element should always have same left position and width as original element. | |
orgElement = $('.original'); | |
coordsOrgElement = orgElement.offset(); | |
leftOrgElement = coordsOrgElement.left; | |
widthOrgElement = orgElement.css('width'); | |
$('.cloned').css('left',leftOrgElement+'px').css('top',0).css('width',widthOrgElement).show(); | |
$('.original').css('visibility','hidden'); | |
} else { | |
// not scrolled past the menu; only show the original menu. | |
$('.cloned').hide(); | |
$('.original').css('visibility','visible'); | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment