Element Visibility
Fire a server handler when an element scrolls into or out of the viewport.
Overview
Element Visibility wraps the browser's IntersectionObserver API. Bind hlivekit.OnElementVisible to an element and your handler runs on the server every time that element's visibility in the viewport changes, with no polling and no scroll-event listeners of your own to write.
API
hlivekit.OnElementVisible(handler l.EventHandler) *l.ElementGroup— fireshandlerevery time this element's visibility changes.hlivekit.OnElementVisibleOnce(handler l.EventHandler) *l.ElementGroup— fires once, then removes itself.hlivekit.ElementVisible() l.Attributer— enable visibility tracking on an element without attaching a handler.hlivekit.ElementVisibleRemove(tag l.Adder)— stop tracking an element's visibility.
Use case
Infinite scroll: put a sentinel element at the bottom of a feed and load the next page with OnElementVisibleOnce the moment it enters the viewport, instead of tracking scroll position by hand. The same hook also works for lazy-loading images or marking a section as "read" once the user has actually scrolled to it.
Code sample
feed := hlivekit.NewComponentList("div")
// A sentinel at the bottom of the feed triggers the next page load
// the moment it scrolls into view.
sentinel := l.NewComponent("div",
hlivekit.OnElementVisibleOnce(func(ctx context.Context, e l.Event) {
for _, item := range fetchNextPage() {
feed.AddItem(l.NewComponentMountable("div", item.Title))
}
}),
)
page.DOM().Body().Add(feed, sentinel)