最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ruby on rails - How can I execute JavaScript when a new Turbo Frame is loaded - Stack Overflow

programmeradmin7浏览0评论

I am using Turbo Frames in my Rails app and have, on every page

<turbo-frame id="messagesFrame" src="/chats">
</turbo-frame>

This loads in fine, and when a link is clicked replaces the frame as expected. In this frame I have set overflow-y: scroll, creating a scrollable frame on the page. Every time a new page is loaded in the frame, I want it to scroll to the bottom. How can I achieve this? Ideally with vanilla JavaScript.

I am using Turbo Frames in my Rails app and have, on every page

<turbo-frame id="messagesFrame" src="/chats">
</turbo-frame>

This loads in fine, and when a link is clicked replaces the frame as expected. In this frame I have set overflow-y: scroll, creating a scrollable frame on the page. Every time a new page is loaded in the frame, I want it to scroll to the bottom. How can I achieve this? Ideally with vanilla JavaScript.

Share Improve this question asked Apr 29, 2021 at 10:05 tsvallendertsvallender 2,9747 gold badges39 silver badges48 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 18

You could do this in several ways.

Turbo should fire a turbo:before-fetch-request and turbo:before-fetch-response on the document when lazy loaded frames, or links that trigger a frame reload.

You could do something like:

document.addEventListener("turbo:before-fetch-response", function (e) {
  let frame = document.getElementById("messagesFrame");
  if (frame.plete) {
   frame.scrollTo(0, frame.scrollHeight)
  } else {
    frame.loaded.then(() => frame.scrollTo(0, frame.scrollHeight))
  }
})

Sources: Turbo events => https://turbo.hotwired.dev/reference/events

Frame.plete and Frame.loaded => https://turbo.hotwired.dev/reference/frames


I suggest the above method because you specified vanilla Javascript. The remended way for most Turbo related things is to use StimulusJS.

You could write a Stimulus (https://stimulus.hotwired.dev/) controller that you attach to an element in the body that shows inside the TurboFrame, and in the connect method, do the same.

That way, whenever the content inside the frame is refreshed the Stimulus controller will run, and you don't have to worry about the order of the events being fired.

发布评论

评论列表(0)

  1. 暂无评论