Skip to content

Instantly share code, notes, and snippets.

@AnatoliyAkhmatov
Last active January 9, 2021 10:21
Show Gist options
  • Save AnatoliyAkhmatov/d557c16891ac9890c1a19d19779b0192 to your computer and use it in GitHub Desktop.
Save AnatoliyAkhmatov/d557c16891ac9890c1a19d19779b0192 to your computer and use it in GitHub Desktop.
window.stick = (el, top_el = null, bottom_el = null) => {
var parent = el.parentNode
if (!top_el) top_el = parent
if (!bottom_el) bottom_el = parent
window.addEventListener('scroll', debounce(() => {
var top = window.pageYOffset
var bottom_stop = $(bottom_el).offset().top
var top_stop = $(top_el).offset().top
if (top > top_stop) {
$(el).css('width', el.offsetWidth)
el.classList.add('fixed')
if ((!el.classList.contains('bottom') && (top + el.offsetHeight >= bottom_stop))) {
var new_top = bottom_stop - top_stop
new_top += $(top_el).parent().height()
new_top -= el.offsetHeight
el.classList.add('bottom')
$(el).css('top', new_top)
} else {
var new_top = bottom_stop - el.offsetHeight
if (top < new_top) {
el.classList.remove('bottom')
$(el).css('top', '')
}
}
} else {
el.classList.remove('fixed')
$(el).css('width', '')
}
}, 10))
}
q('[data-stick]').forEach(el => {
var id = $(el).data('stick')
var top_el = q1(".t-stick-top[data-id='" + id + "']")
var bottom_el = q1(".t-stick-bottom[data-id='" + id + "']")
stick(el, top_el, bottom_el)
})
<div class="t-stick-bottom" data-id='1'></div>
<div class="t-stick-top" data-id='1'></div>
<div class="t-products" data-stick='1'></div>
&.fixed
position: fixed
top: 0
&.bottom
position: absolute
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment