Skip to content

Instantly share code, notes, and snippets.

@rc1
Last active July 3, 2017 13:44
Show Gist options
  • Save rc1/3828a24d31a9ee7dc70a00a153f07039 to your computer and use it in GitHub Desktop.
Save rc1/3828a24d31a9ee7dc70a00a153f07039 to your computer and use it in GitHub Desktop.
Peek content below the fold using jquery
// Peak content from below the fold above the fold
var defaultPeekAmount = 80;
$( '[data-peek]' )
// Find the closest
.sort( ( a, b ) => {
if( a.getBoundingClientRect().top - $( window ).height() < b.getBoundingClientRect().top - $( window ).height() + $( window ).scrollTop() ) {
return -1;
} else {
return 1;
}
})
// Check it's not `data-peek='false'`
.filter( ( idx, el ) => $( el ).data( 'peek' ) !== false )
// Take the first one
.first()
// Only take below the screen
.filter( ( idx, el ) => {
var peekAmount = $( el ).data( 'peekAmount' ) || defaultPeekAmount;
return el.getBoundingClientRect().top - $( window ).height() + $( window ).scrollTop() > - peekAmount;
})
// Make it peak above
.each( ( idx, el ) => {
var $el = $( el );
var $window = $( window );
$el.children().wrapAll( '<div class="peek"></div>' );
var $peek = $el.find( '.peek' );
var peekAmount = $el.data( 'peekAmount' ) || defaultPeekAmount;
var firstUpdate = true;
var update = () => {
var distanceBelow = Math.round( $el[ 0 ].getBoundingClientRect().top - $window.height() );
$peek.css({
transform: 'translate3d(0,-' + Math.max( 0, Math.round( distanceBelow + peekAmount ) ) + 'px, 0)' ,
top: peekAmount,
transition: firstUpdate ? '' : 'transform 0.2s',
zIndex: 1
});
firstUpdate = false;
};
update();
$window.on( 'scroll', update );
$window.on( 'resize', update );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment