Skip to content

Instantly share code, notes, and snippets.

@yratof
Last active November 9, 2016 13:12
Show Gist options
  • Save yratof/6230160 to your computer and use it in GitHub Desktop.
Save yratof/6230160 to your computer and use it in GitHub Desktop.
Sticky header after X scroll
jQuery( function($) {
// This element will stick...
var $sticky = $( '#stick_me' );
// ...When you pass this point
var $trigger = $( '#turn_on_sticky' );
// If the element exists...
if ( $sticky.length > 0 ) {
// Get the top
var top = $trigger.offset().top - parseFloat( $sticky.css( 'margin-top' ).replace( /auto/, 0 ) );
function check_if_sticky_triggered(){
// Find out where our element is
var y = $sticky.scrollTop();
// Has the element passed the checkpoint?
if ( y >= top ) {
$sticky.addClass( 'fixed' ); // If so, add the fixed class
} else {
$sticky.removeClass( 'fixed' ); // Otherwise remove it
}
}
// Check on load where you are:
$( document ).ready( function(){
check_if_sticky_triggered();
});
// When the window scrolls check again
$( window ).scroll( function() {
check_if_sticky_triggered();
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment