summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/lib/utils/sticky.js
blob: 098afcfa1b49488561e817c87f43d735a07dc6d2 (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
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, stickyTop, insertPlaceholder = true) => {
  if (!el) return;

  if (typeof CSS === 'undefined' || !(CSS.supports('(position: -webkit-sticky) or (position: sticky)'))) return;

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