scrollTo()/scrollIntoView() doesn't work after visit
See original GitHub issueI need to scroll to a certain element on a page right after it loads. I use a Stimulus controller which listens to the turbo:load
event, then searches for the element and, if found, scrolls it into view.
This works when I call the page for the first time or refresh the browser. But whenever I reach the page through Turbo.visit()
, it simply does not scroll although the controller function gets called.
(I’ve tried scrollTo()
, scrollIntoView()
and also location.href = '#anchorId';
. The controller function finds the correct element and gets its correct position on the page.)
It seems that Turbo’s scroll position restoration functions are interfering. Is there a way to prevent those? Or is there an event that fires after?
(Also happens with v7.0.0-rc.2.)
Issue Analytics
- State:
- Created 2 years ago
- Reactions:3
- Comments:5 (2 by maintainers)
Top GitHub Comments
I think @michalsznajder is right, but I’m not sure making
turbo:load
the last event would solve this problem.You could get to something similar today by doing something like this in
turbo:render
:The problem with that is that Turbo has already scrolled to the top so you get this flicker effect.
Ideally it would be cool to have a way to signal Turbo to not scroll, but I’m not sure how that would look like.
I have the same problem. I think this boils down to
turbo:load
being fired before scroll restore logic kicks in.Related code: ‘Visit.loadResponse()’ calls ‘Visit.render()’. In promise for
Visit.render()
Visit.complete()
is called that dispatchesturbo:load
. LaterVisit.render()
calls ‘performScroll()’ that modifies scroll position so your Stimulus controller is no longer working.Maybe
turbo:load
could be dispatched as last event in Turbo Drive?Also #312 is related.