Skip to content

Instantly share code, notes, and snippets.

@ebuildy
Last active January 22, 2019 09:13
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 ebuildy/9106572633be035f1c0caa0f1c0c8681 to your computer and use it in GitHub Desktop.
Save ebuildy/9106572633be035f1c0caa0f1c0c8681 to your computer and use it in GitHub Desktop.
Simple & pure JS sticky

Will stick vertically element with class "sticky-item".

Usage is for Table > sticky cells, so this code check element left to create sticky groups.

.sticky-fixed {
position: fixed;
top: 5px;
background: white;
}
const getElementAbsoluteOffset = (el) => {
var rect = el.getBoundingClientRect(),
scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
scrollTop = window.pageYOffset || document.documentElement.scrollTop;
return { top: rect.top + scrollTop, left: rect.left + scrollLeft }
}
export default class Sticky {
constructor() {
this.items = []
this.handleWindowScroll = this.handleWindowScroll.bind(this)
}
start() {
this.end()
this.windowOnScrollListener = window.addEventListener("scroll", this.handleWindowScroll)
}
end() {
window.removeEventListener("scroll", this.handleWindowScroll)
}
handleWindowScroll(e) {
const windowY = window.pageYOffset
var lastStickyFound = {}
const items = [...document.getElementsByClassName("sticky-item")]
.map(element => ({
...getElementAbsoluteOffset(element.parentElement.parentElement),
cell: element.parentElement.parentElement,
element: element,
classList: element.classList
}))
.sort((a, b) => b.top - a.top)
for (var i in items) {
const {classList, top, left} = items[i]
if (top <= windowY && !lastStickyFound.hasOwnProperty(left)) {
classList.add("sticky-fixed")
lastStickyFound[left] = "ok"
} else {
classList.remove("sticky-fixed")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment