|
(function () { |
|
"use strict" |
|
|
|
stick('#stickme','bottom'); |
|
|
|
function stick(ele, position = 'top') { |
|
|
|
// get the element to be stuck |
|
const stick = document.querySelector(ele); |
|
const stickPos = stick.getBoundingClientRect(); |
|
const stickBottom = stickPos.top + stick.clientHeight; |
|
|
|
// get the parent |
|
const stickParent = stick.parentNode; |
|
const stickParentPos = stickParent.getBoundingClientRect(); |
|
|
|
// on debounce scroll |
|
window.addEventListener('scroll', debounce(function(){ |
|
|
|
// get current scroll pos |
|
let scrollPos = document.documentElement.scrollTop || document.body.scrollTop; |
|
|
|
// current viewport dimentions |
|
let viewportHeight = document.documentElement.clientHeight; |
|
let viewportBottom = scrollPos + viewportHeight; |
|
|
|
// rang to stick |
|
if (viewportBottom > stickBottom) { |
|
stick.classList.add('stick'); |
|
} else { |
|
stick.classList.remove('stick'); |
|
} |
|
|
|
// if the bottom of the viewport is past the sticky element's parent bottom |
|
// anchor to bottom of parent |
|
if (viewportBottom > (stickParentPos.top + stickParentPos.height)) { |
|
stick.classList.add('stick--is-stuck'); |
|
} else { |
|
stick.classList.remove('stick--is-stuck'); |
|
} |
|
})); |
|
|
|
// slow yo role |
|
function debounce(func, wait = 5, immediate = true) { |
|
var timeout; |
|
return function() { |
|
var context = this, args = arguments; |
|
var later = function() { |
|
timeout = null; |
|
if (!immediate) func.apply(context, args); |
|
}; |
|
var callNow = immediate && !timeout; |
|
clearTimeout(timeout); |
|
timeout = setTimeout(later, wait); |
|
if (callNow) func.apply(context, args); |
|
}; |
|
}; |
|
} |
|
} ()); |