Created
November 19, 2016 15:01
-
-
Save pravdomil/0910fbdedee0b77929a7a1ee5c6e85d5 to your computer and use it in GitHub Desktop.
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
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