Turbo Frames - Lifecycle of a Lazy Loaded Frame

Manage view state with Turbo Frames and Stimulus.

View Solution on Patreon
Turbo Frames - Lifecycle of a Lazy Loaded Frame

Premise

Turbo Frames can be lazily loaded triggered by an IntersectionObserver, as is probably widely known. But aside from optimizing our page load performance, we can also utilize their lifecycle to trigger custom interactions.

Challenge

In this challenge, we are looking at a mock legal document, with a fixed TOC on the left (careful, this is hidden on a mobile device!) and some scrolling content on the right. Each paragraph is wrapped in a lazy-loaded frame, for demonstration purposes.

Using Stimulus and Turbo Frame’s events, we want to toggle each frame as “seen” in the TOC once it has finished loading.

Your entrypoint is the user-interaction Stimulus controller’s markAsSeen action:

Implement a behavior that will

  • toggle the seenValue, and
  • add a check mark (provided as a string)

You will have to also declare the correct action listening on the correct event in the <li> in the markup: https://stackblitz.com/edit/turbo-frames-lifecycle?file=index.html%3AL71,controllers%2Fuser_interaction_controller.js

Here’s a rendering of the final result:

An Animation Showing a Reset of the Scroll Position after Navigation

Some references you might want to take a look at:

https://stimulus.hotwired.dev/reference/values

https://turbo.hotwired.dev/reference/events

Caveats

Make sure to add the checkmark only once!

Teaser

How would you implement sending a PATCH request to the server that toggles the read status for each paragraph?

More from

Faceted Search with Stimulus and Turbo Frames
10 December 2024

Harness the power of Stimulus and Turbo Frames to drive a simple but powerful faceted search solution

Turbo Frames - Markdown Preview
08 October 2024

Typeahead previews of markdown by simple Turbo Frame rerendering

Turbo Frames - Render Flash Messages Upon Form Submission
27 August 2024

Intercept form submission responses to render flash messages that are outside the originating Turbo Frame

Cookies
essential