BigW Consortium Gitlab

sticky.js 1.3 KB
Newer Older
1 2 3 4 5 6 7 8
export const createPlaceholder = () => {
  const placeholder = document.createElement('div');
  placeholder.classList.add('sticky-placeholder');

  return placeholder;
};

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

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

15
    el.classList.add('is-stuck');
16 17 18 19 20 21 22

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

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

25
    if (insertPlaceholder && el.nextElementSibling && el.nextElementSibling.classList.contains('sticky-placeholder')) {
26 27
      el.nextElementSibling.remove();
    }
28 29 30
  }
};

31
export default (el, insertPlaceholder = true) => {
Phil Hughes committed
32 33
  if (!el) return;

34 35 36 37 38 39
  const computedStyle = window.getComputedStyle(el);

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

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

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