Skip to content

Instantly share code, notes, and snippets.

@VinceVachon
Created November 24, 2016 16:07
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 VinceVachon/2cae128d4f46d876f99171e34d425aab to your computer and use it in GitHub Desktop.
Save VinceVachon/2cae128d4f46d876f99171e34d425aab to your computer and use it in GitHub Desktop.
Fix an element on scroll until it reach a certain position in the page
function scrollToFixedPos() {
// containter to fix to and element to scroll
const $refElToFixTo = $('.ref-el-to-fix-to');
const $elToFix = $('.el-to-fix')
//$padding is 15% of window height to adapt the placement of the scrolling element
const $wHeight = $(window).innerHeight();
const $padding = $wHeight * 15 / 100;
//default top position of the scrolling element
let $elTop = 70;
$(window).on('scroll', function () {
if ($(window).scrollTop() >= $refElToFixTo.offset().top) {
$elTop = ($(window).scrollTop() - $refElToFixTo.offset().top) * -1 + $padding;
$elToFix.css({
top: $elTop + 'px'
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment