I have a Stimulus controller on a form, on connect() I check if a scrolltoValue is not empty, if it is not I would like to scroll to this value element. If on connect() I call this.scrollToTarget() it just scrolls to the top, if I do setTimeout(() => this.scrollToTarget(), 0); it scrolls to the target but it starts scrolling to the top, so I can see 2 scrolls, the starting scroll to the top and then the scroll to the element.
Is there a way to disable scroll to top after form submit?
For what it’s worth, I’m going to try to solve this for the time-being with a search-parameter. Instead of using the fragment, I’m going to use ?scrollTo={ id } in the forwarding URL. Then, I’ll have a turbo:load event-handler that scrolls to the given element:
// Scroll down to the desired element (via ID selector).
document.documentElement.addEventListener(
"turbo:load",
function handleLoad( event ) {
var searchParams = new URLSearchParams( location.search );
var scrollTo = searchParams.get( "scrollTo" );
if ( ! scrollTo ) {
return;
}
document.querySelector( `#${ scrollTo }` )
?.scrollIntoView()
;
}
);
Eventually, when Hotwire fixes the hash / fragment issue, I can just swap the query-string value for a fragment value, easy peasy.