i'm having a little trouble trying to force a scrolling with javascript when a new partial are rendered by turbo-frame, the page have an small form, and when the button are clicked, he triggers an event who render a new form, and when a new form are added, if the amount of forms are enough, he will create an vertical scroll.
So i try to add an event listener on button click, so when he clicks, he catch the container scrollHeight and compares to clientHeight, if is greater, he will do the attribution of element scrollTop, this is the code:
button.addEventListener("click", function (e) {
let container = document.querySelector("#container-travellers")
if (container.scrollHeight > container.clientHeight) {
console.log('should scroll')
container.scrollTop = container.scrollHeight;
}
})
i searched a lot, and try to do that with turbo events like autoscroll
property of turbo frame, or some event like turbo:submit-end
, but on this both events, the scroll isn't happening, only the console log, comproving the conditional is working.
if thats important, this is the html code of the turbostream and turbo frame call
<%= turbo_stream_from 'checkout_stream' %>
<div id="container-travellers" class="shadow-md flex flex-col rounded-md bg-white p-2 w-full max-h-[690px] gap-2 scroll-smooth overflow-auto" data-autoscroll-block="end">
<%= turbo_frame_tag 'travellers', id:'travellers_frame', class:"flex flex-col gap-4" do %>
<%= render partial: 'travellers/traveller_form'%>
<% end %>
<%= link_to "Add New", add_new_traveller_path, id:'new_traveller', class:"w-full text-center bg-[#{tw_color_purple('600')}] py-1 text-white hover:bg-[#{tw_color_purple('700')}] rounded", data: {
turbo_method: :post,
} %>
</div>
SOLUTION (not the best):
After i tried find some solutions with Turbo helpers, events and attributes and none of these worked, i run into javascript, and make it work, listen to the event DOMNodeInserted
, so, when a new partial are streamed and append on the frame, the event are triggered and run the scroll function.
It's not the best solution i know, but for me, fixed the problem.