From ea65ae01a99f6a48a7dea761b90d3ecd2305d004 Mon Sep 17 00:00:00 2001 From: Kuba Orlik Date: Tue, 2 Jul 2024 19:06:35 +0200 Subject: [PATCH] Handle changing amoutn of elements --- .../horizontal-scroller.stimulus.ts | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/back/routes/common/horizontal-scroller/horizontal-scroller.stimulus.ts b/src/back/routes/common/horizontal-scroller/horizontal-scroller.stimulus.ts index e1a5da5..fce7fdb 100644 --- a/src/back/routes/common/horizontal-scroller/horizontal-scroller.stimulus.ts +++ b/src/back/routes/common/horizontal-scroller/horizontal-scroller.stimulus.ts @@ -12,9 +12,11 @@ export default class HorizontalScroller extends Controller { visibility: number[]; + intersectionObservers: IntersectionObserver[]; + connect() { this.visibility = this.elementTargets.map(() => 0); - [0, 0.5, 0.9, 1].forEach((threshold) => { + this.intersectionObservers = [0, 0.5, 0.9, 1].map((threshold) => { const observer = new IntersectionObserver( (events) => this.handleIntersection(events), { @@ -23,12 +25,23 @@ export default class HorizontalScroller extends Controller { threshold, } ); - this.elementTargets.forEach((e) => observer.observe(e)); + return observer; }); + this.observe(); this.refreshMarkers(); } + markerTargetConnected() { + this.observe(); + } + + observe() { + this.intersectionObservers?.forEach((observer) => + this.elementTargets.forEach((e) => observer.observe(e)) + ); + } + handleIntersection(events: IntersectionObserverEntry[]) { events.forEach((event) => { const element_index = this.elementTargets.indexOf(