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

Scrolling Lyrics using Turbo Frames
09 April 2024

Create a "scrolling lyrics" animation using Turbo Frames and View Transitions

Turbo Frames - Inline Edit
27 February 2024

Manage Inline Editing with Turbo Frames and Cookies

Turbo Frames - Typeahead Search
07 November 2023

Update filter results using eager loading Turbo Frames.

Cookies
essential