From 4aea4b3b93bdc0cb1cf7d042845a1b75e35deab5 Mon Sep 17 00:00:00 2001 From: Keith Cirkel Date: Mon, 18 Apr 2016 15:28:25 +0100 Subject: [PATCH] fix: ensure position of sticky element stops at container bottom This fix sets the top to a maximum of the wrapper's container height, minus the height of the primary element. In other words, the primary cannot move beyond its parent container. This is truer to the behaviour of `position: sticky` in browsers that support it. Fixes #4 --- src/sticky-position.js | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/src/sticky-position.js b/src/sticky-position.js index 841c051..a84152a 100644 --- a/src/sticky-position.js +++ b/src/sticky-position.js @@ -20,7 +20,7 @@ export default function({ function stick() { if (isSticky === true) return; - primary.style.position = 'fixed'; + primary.style.position = 'absolute'; isSticky = true; } @@ -58,24 +58,22 @@ export default function({ function update() { const rect = wrapper.getBoundingClientRect(); const sticky = rect.top < top; - + if (sticky) { placeholder.style.height = rect.height + 'px'; - + if (computeWidth) { placeholder.style.width = rect.width + 'px'; } - - var parentRect = wrapper.parentNode.getBoundingClientRect(); - - primary.style.top = Math.min(parentRect.top + parentRect.height - rect.height, top) + 'px'; - primary.style.width = computeWidth ? rect.width+'px' : '100%'; - primary.style.left = rect.left + 'px'; - + + const primaryRect = primary.getBoundingClientRect(); + primary.style.top = Math.min((rect.height - primaryRect.height), Math.max(Math.abs(rect.top), top)) + 'px'; + primary.style.width = computeWidth ? rect.width + 'px' : '100%'; + stick(); } else { unstick(); - } + } } function destroy() { @@ -98,4 +96,4 @@ export default function({ destroy, }; } -} \ No newline at end of file +}