What is the best way to remember the scroll position on main (categories) page?

As I see many pages on Discourse remember the scroll position.
But the categories page opens on top every time. And in case when it’s the main page and there are a lot of categories there - it provides not the best UX.

F.e. I saw FEATURE: Remember scroll position in private message lists by markvanlan · Pull Request #8212 · discourse/discourse · GitHub commit by @markvanlan
Do you know - what is the shortest way to do the same for the categories page?

As I understand from this old topic -

dev team prefers to keep the Categories page to open on top, not like other pages.

So probably it’s better to find a way to implement Categories scroll fix as a separate theme component. What is the best approach in your opinion?

Or maybe someone has already done it?


1 Like

I believe this could be done with a theme component. I’m not sure how technical you are but I can give a basic outline of how this could be accomplished.

Using the onPageChange API, you could check to see if the current page is the categories page. If so, check localStorage for the user’s last scroll position on the page, and scroll to that position if it exists. At that point add an event listener to the window to store the user’s scroll position in localStorage. In the onPageChange, if the user is not on the categories page, remove the event listener.

1 Like

Thank you @markvanlan - I will try.
I’m a programmer but less experienced in frontend.

Please keep this topic open for some time - maybe there is someone who already did this.

1 Like

A quick and dirty solution for now - maybe it may help someone later.

<script type="text/discourse-plugin" version="0.8">

api.onPageChange((url) => {
    window.removeEventListener("scroll", saveScroll, {passive: true,});
    if (url === "/" || url === "/categories"){
        window.addEventListener("scroll", saveScroll, {passive: true,});

function restoreScroll() {
    var pos = sessionStorage.getItem("categoriesScrollPosition");
    if (pos != 0) {
        window.scrollTo(0, pos);

function saveScroll() {
    if (window.scrollY != 0) {
        sessionStorage.setItem("categoriesScrollPosition", window.scrollY + 1);
1 Like