1

I would like to have a link inside a turbo frame that works as usual (i.e. by default, when the link is clicked then the frame targets itself to load content provided at the given link url) but with the addition to scroll the page at a given anchor.

I tried the following without success:

<turbo-frame id="turbo_frame_id" src="http://localhost:3000/articles/2023/edit">
  <div id="anchorLink">

    Content

    ... long content ...
    
    
    <%= link_to("Load frame and go to anchor", edit_article_path(article, :anchor => 'anchorLink')) %>
  </div>
</turbo-frame>

I also tried to move the <div> with the anchor and the <turbo-frame> elements around, without success.

<div id="anchorLink">
  <turbo-frame id="turbo_frame_id" src="http://localhost:3000/articles/2023/edit">
    Content ...

    <%= link_to("Load frame and go to anchor", edit_article_path(article, :anchor => 'anchorLink')) %>
  </turbo-frame>
</div>

With the above code the result is the same: when I click the link "Load frame and go to anchor" then the frame loads the content from edit_article_path(article, :anchor => 'anchorLink') as expected but it doesn't scroll the page at "anchorLink".

I seen on GitHub many issues about anchored links (almost all resolved or closed) but they are about navigation and not about scrolling the page.

How can I make the frame to load the content and scroll to the anchor after/while loading? Should I use custom JS/Stimulus to "mimic" the Turbo Frame content loading and get scrolling to the anchor? Or is there something in Turbo Frame (which I'm not aware of) that can be used to scroll the page after navigation?

Backo
  • 18,291
  • 27
  • 103
  • 170
  • I think what you need to do here is add an event listener to the `turbo:frame-render` event. Per the docs its fired on the document and not the elements themselves. So something along the lines of `document.addEventListener('turbo:frame-render', (event) => { if (!event.target.matches('.scroll-to') return; event.target.scrollIntoView(); });` – max Apr 06 '23 at 15:52

0 Answers0