Skip to content

Instantly share code, notes, and snippets.

@pravdomil
Created November 19, 2016 15:01
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 pravdomil/0910fbdedee0b77929a7a1ee5c6e85d5 to your computer and use it in GitHub Desktop.
Save pravdomil/0910fbdedee0b77929a7a1ee5c6e85d5 to your computer and use it in GitHub Desktop.
new class {
constructor() {
this.nodes = this.find('.position_sticky').map(el => { return { el, placeholder: null } })
window.addEventListener('scroll', e => this.go(), { passive: true })
this.go()
}
go() {
this.nodes.forEach(node => this.check(node))
}
check(node) {
var rect = (node.placeholder ? node.placeholder : node.el).getBoundingClientRect()
if (rect.top < 0 && !node.placeholder) {
this.stick(node, rect)
}
else if (rect.top > 0 && node.placeholder) {
this.unstick(node)
}
}
stick(node, rect) {
node.placeholder = document.createElement('div')
node.placeholder.style.width = rect.width + 'px'
node.placeholder.style.height = rect.height + 'px'
node.placeholder.style.opacity = 0
node.el.parentNode.insertBefore(node.placeholder, node.el)
node.el.style.position = 'fixed'
}
unstick(node) {
node.placeholder.remove()
node.placeholder = null
node.el.style.position = ''
}
find(sel) {
return Array.prototype.slice.call(document.querySelectorAll(sel))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment