Created
November 24, 2016 16:07
-
-
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
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
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