summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/lib/utils/sticky.js
blob: 43a808b6ab3b5bddb4481b2a2597d0f18a32b217 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
export const isSticky = (el, scrollY, stickyTop) => {
  const top = el.offsetTop - scrollY;

  if (top === stickyTop) {
    el.classList.add('is-stuck');
  } else {
    el.classList.remove('is-stuck');
  }
};

export default (el) => {
  if (!el) return;

  const computedStyle = window.getComputedStyle(el);

  if (!/sticky/.test(computedStyle.position)) return;

  const stickyTop = parseInt(computedStyle.top, 10);

  document.addEventListener('scroll', () => isSticky(el, window.scrollY, stickyTop), {
    passive: true,
  });
};