Need to automatically go at the top of the page

Hi all,

I’ve an anchor link at the top of the page #Automatic.
Image that the user is in the middle of the page and some code is executing.
Is it possible to automatically send the user to the top of the page (exploiting the anchor link or directly via html code?)
The button is a streamlit button so something like

st.markdown("[Section 1](#section-1)")

Doesn’t work for me because the user is supposed to click it.
Ideally this is what I need

some code here
some code here
line that brings the user to the top of the page without he does nothing
some code

Thank you


I think your best bet is

st.markdown('# Section 1')

st.markdown('Lorem ipsum')

# As a text link
st.markdown('[Back to Top](#section-1)')

# As an html button (needs styling added)
st.markdown(''' <a target="_self" href="#section-1">
                        Back to Top
                </a>''', unsafe_allow_html=True)

When you click a Streamlit button, it will by definition rerun the app. You can observe if you manually type in a url with the section anchor that the anchor goes away as the page finishes loading.

1 Like


I’m sorry, your solution works if the user, as you said, click the streamlit button to go on top. What I’ looking for is something that perform this action automatically. The same concept that you mentioned but without clicking anything, just a line of code that “sends” you at the top while you’re not touching anything.

Thank you

1 Like

You can inject javascript. Try this, making sure to scroll down before the page loads to observe (that’s why I put the sleep in there). However, the javascript only executes when it is added to the page on first load. I am unclear on your intended use, but if you conditionally remove the javascript so that you can render it from scratch when you need it you can get its effect more than once.

import streamlit as st
import time

st.write('meow ' * 10_000)

js = '''
    var body = window.parent.document.querySelector(".main");
    body.scrollTop = 0;


Hi, thanks for replying. I was actually desperate in finding a WA for the constant reloading of the page when something changes its state…I think that I’m developing (I guess) pages that are too heavy for streamlit and becasue fo this I’m constantly fighting with the fact that even to leave an “heavy” page, streamlit still needs to reload it entirely and I wanted to avoid a visualization issue by “bringing” automatcally the user to the top.

I solved by inserting the “heavy” code in an st.empty() object and laucnhing an “onclick” function that was cleaning it.

Thanks again :slight_smile: