How To: Turbolinks 5 Scroll Position Persistence

Sedad Kosovac
2 min readOct 22, 2018

--

Default behavior when we click on a link with Turbolinks is to go to that link and scroll to the top to replicate real page change, even if only thing that happens is ajax request that after a success appends new page body and browser URL history is changed.

But what if we don`t want that default scroll. Well this is how we do it.

What We Have

What We Want

View

We only add data-turbolinks-scroll = false so we can distinguish between those we do want to remove default scroll.

JavaScript

Explanation

We add a property to turbolinks object sort so we have somewhere to add vertical position from current document scroll element when click or submit happens.

On every turbolinks:load we check if scroll top is set. If it is we scroll to that position and last thing we do is make sure to set empty object to scroll property.

That is it ;)

--

--