Created
September 27, 2017 18:33
-
-
Save SigurdMW/bf502636f44b1cfd9126d3add01d0d83 to your computer and use it in GitHub Desktop.
Create sticky elements within a container in vanilla javascript
This file contains hidden or 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 stickySharingIcons() { | |
if (window.innerWidth > 768) { | |
const stickyIcons = document.querySelectorAll(".sticky-sharing-icons"); | |
if (stickyIcons.length > 0) { | |
for (var i = 0; i < stickyIcons.length; i++) { | |
makeIconsSticky(stickyIcons[i], document.querySelector(".article-page-content")); | |
} | |
} | |
} | |
} | |
export function makeIconsSticky(stickyEl, target) { | |
const initialLeftPost = stickyEl.style.left; | |
const initPosLeft = stickyEl.getBoundingClientRect().left; | |
document.addEventListener("scroll", () => { | |
updateSticky(stickyEl, target, initialLeftPost, initPosLeft); | |
}); | |
} | |
export function updateSticky(el, target, leftStyle, leftAbs) { | |
const articleVwTop = target.getBoundingClientRect().top; | |
const stickyHeight = el.offsetHeight; | |
if (articleVwTop < 0 && (articleVwTop * -1) <= (target.offsetHeight - stickyHeight)) { | |
el.style.position = "fixed"; | |
el.style.left = leftAbs + "px"; | |
el.style.top = "0px"; | |
} else { | |
el.style.position = "absolute"; | |
el.style.left = leftStyle; | |
if (articleVwTop < 0 && articleVwTop <= (target.offsetHeight - el.offsetHeight)) { | |
el.style.top = (target.offsetHeight - el.offsetHeight) | |
+ "px"; | |
} | |
} | |
} | |
export default stickySharingIcons |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment