Using IntersectionObserver via the svlete-intersection-observer library to lazy-load content once and trigger changes to a content block when it comes into view (intersects), while also passing intersecting element as prop to a sticky element on the page via a Svelte store.
threshold="0"
),
we load the element. This happens only once (once="true"
),
which makes sense because we don't need to lazy-load more than once.
The lazy loading bit is achieved by adding the condition if intersecting
as then we will only display the DOM element if it intersects the viewport.
threshold="0.7"
),
it will change colour.
.style('background', d => intersecting ? '#ee3e3e' : '#6b6065')
in ContentElement.)
threshold
prop of the IntersectionObserver here is
not the viewport threshold, but the proportion (0 to 1) of the intersecting element that
has to be visible in the viewport to trigger the intersecting prop to become true.
currentElNum
variable as a svelte store.currentElNum
to the id corresponding
to the data entry bound to that element each time the second IntersectionObserver's
intersection condition is satisfied.
In other words, when an element is 70% visible in the viewport,
currentElNum
gets updated with the id for the data entry bound to that element.
currentElNum
and its content gets dynamically updated based on it.
Using just the built-in Intersection Observer API, affecting a change in the DOM when an element intersects the viewport.
IntersectionObserver
class takes in two
parameters, an observerCallback
and observerOptions
.
observerOptions
are things like the threshold at which an element is
considered intersecting (as a proportion of the total height of the element).
These are static properties.
observerCallback
determines what happens when the intersection event occurs.
In our case, we define a inView
variable, which keeps track if the element is in view
and update it from that callback function.
inView
, it would need to
be wrapped in a reactive declaration. For example, if we then wanted to draw a D3 graph, we'd need to
make the code reactive, just like in other examples here.
active
on the observed element, where active
is defined in CSS and determines how the appearance of the changes when inView = true
.
inView
only being able to affect a change if it is
wrapped in a reactive statement doesn't apply in this case. This is because Svelte-native DOM changes
(e.g. DOM-events from Svelte like on:click
or class conditions like class:active
etc.)
are reactive by design.