Reputation: 18871
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?
Upvotes: 4
Views: 1332
Reputation: 52198
It's a known issue with turbo.
I'm using this workaround.
Paste this into application.js
document.addEventListener("turbo:load", function() {
const params = new URLSearchParams(window.location.search);
if (params.get('scroll_to')) {
const element = document.getElementById(params.get('scroll_to'));
if (element) element.scrollIntoView();
}
});
then instead of
redirect_to your_path(anchor: "your-id")
use
redirect_to your_path(scroll_to: "your-id")
I've been using this for a while now and haven't had any problems, seems to work nicely.
Upvotes: 1