debian-mirror-gitlab/app/assets/javascripts/lib/utils/sticky.js

40 lines
1.3 KiB
JavaScript
Raw Normal View History

2018-03-17 18:26:18 +05:30
export const createPlaceholder = () => {
const placeholder = document.createElement('div');
placeholder.classList.add('sticky-placeholder');
return placeholder;
};
export const isSticky = (el, scrollY, stickyTop, insertPlaceholder) => {
2017-09-10 17:25:29 +05:30
const top = Math.floor(el.offsetTop - scrollY);
2018-03-17 18:26:18 +05:30
if (top <= stickyTop && !el.classList.contains('is-stuck')) {
const placeholder = insertPlaceholder ? createPlaceholder() : null;
const heightBefore = el.offsetHeight;
2017-09-10 17:25:29 +05:30
el.classList.add('is-stuck');
2018-03-17 18:26:18 +05:30
if (insertPlaceholder) {
el.parentNode.insertBefore(placeholder, el.nextElementSibling);
placeholder.style.height = `${heightBefore - el.offsetHeight}px`;
}
} else if (top > stickyTop && el.classList.contains('is-stuck')) {
2017-09-10 17:25:29 +05:30
el.classList.remove('is-stuck');
2018-03-17 18:26:18 +05:30
if (insertPlaceholder && el.nextElementSibling && el.nextElementSibling.classList.contains('sticky-placeholder')) {
el.nextElementSibling.remove();
}
2017-09-10 17:25:29 +05:30
}
};
2018-03-17 18:26:18 +05:30
export default (el, stickyTop, insertPlaceholder = true) => {
2017-09-10 17:25:29 +05:30
if (!el) return;
2018-03-17 18:26:18 +05:30
if (typeof CSS === 'undefined' || !(CSS.supports('(position: -webkit-sticky) or (position: sticky)'))) return;
2017-09-10 17:25:29 +05:30
2018-03-17 18:26:18 +05:30
document.addEventListener('scroll', () => isSticky(el, window.scrollY, stickyTop, insertPlaceholder), {
2017-09-10 17:25:29 +05:30
passive: true,
});
};