fix: 🐛 make end detection more robust
Smooth scrolling messes with the detection of isAtEnd. Introduce a debounce to delay updateActiveStates until scroll has actually finished.
This commit is contained in:
parent
a98028b880
commit
c0b42b82d0
1 changed files with 16 additions and 6 deletions
|
@ -8,6 +8,20 @@
|
|||
|
||||
const TOLERANCE = 2;
|
||||
|
||||
const debounce = (fn, delay = 300) => {
|
||||
let timer = 0;
|
||||
const debounced = (...args) => {
|
||||
if (!args) args = [];
|
||||
clearTimeout(timer);
|
||||
|
||||
timer = setTimeout(() => {
|
||||
fn.apply(fn, args);
|
||||
}, delay);
|
||||
};
|
||||
|
||||
return debounced;
|
||||
};
|
||||
|
||||
const isAtStart = () => Math.floor(track.scrollLeft) <= TOLERANCE;
|
||||
const isAtEnd = () => {
|
||||
const { scrollLeft, offsetWidth, scrollWidth } = track;
|
||||
|
@ -41,12 +55,7 @@
|
|||
const prev = () => scrollToIndex(currentIndex - 1);
|
||||
const next = () => scrollToIndex(currentIndex + 1);
|
||||
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
clearTimeout(resizeTimeout);
|
||||
resizeTimeout = setTimeout(() => {
|
||||
scrollToIndex(currentIndex);
|
||||
}, 100);
|
||||
});
|
||||
const resizeObserver = new ResizeObserver(() => debounce(scrollToIndex(currentIndex)));
|
||||
resizeObserver.observe(track);
|
||||
|
||||
const galleryObserver = new IntersectionObserver(
|
||||
|
@ -89,6 +98,7 @@
|
|||
images.forEach((el) => galleryObserver.observe(el));
|
||||
prevButton.addEventListener('click', prev);
|
||||
nextButton.addEventListener('click', next);
|
||||
track.addEventListener('scroll', () => debounce(updateActiveStates(currentIndex)));
|
||||
document.addEventListener('DOMContentLoaded', () => initializeGallery());
|
||||
</script>
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue