summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/lib/utils/sticky.js
blob: 64db42701ce1c1e6fb082cb73f082b4ebed7bc71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
export const createPlaceholder = () => {
  const placeholder = document.createElement('div');
  placeholder.classList.add('sticky-placeholder');

  return placeholder;
};

export const isSticky = (el, scrollY, stickyTop, insertPlaceholder) => {
  const top = Math.floor(el.offsetTop - scrollY);

  if (top <= stickyTop && !el.classList.contains('is-stuck')) {
    const placeholder = insertPlaceholder ? createPlaceholder() : null;
    const heightBefore = el.offsetHeight;

    el.classList.add('is-stuck');

    if (insertPlaceholder) {
      el.parentNode.insertBefore(placeholder, el.nextElementSibling);

      placeholder.style.height = `${heightBefore - el.offsetHeight}px`;
    }
  } else if (top > stickyTop && el.classList.contains('is-stuck')) {
    el.classList.remove('is-stuck');

    if (insertPlaceholder && el.nextElementSibling && el.nextElementSibling.classList.contains('sticky-placeholder')) {
      el.nextElementSibling.remove();
    }
  }
};

export default (el, insertPlaceholder = true) => {
  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, insertPlaceholder), {
    passive: true,
  });
};