Programmatically jump to anchor on same page after clicking button

Hi!
I’m developing a streamlit app where I need the page to automatically focus or scroll to an anchor (‘#report’) in that same page after a button (‘run analysis’) is clicked and the some computation is done. The section of the page with the anchor is generated after pressing the button, and it’s hidden down the page due to other html at the top of it.
Here is a simplified snipper of the code I have

# a lot of other code for input forms and whatnot, hiding the 'report' section
if st.button("run analysis"):
      result = do_some_computing(params...)
      st.header("Report",  anchor="report")
      # do something like scroll_to("report")

I tried with the JS solution in here https://discuss.streamlit.io/t/jump-to-section-of-components-html/34180/4, but I get in the same error of one of the users, that JS doesn’t manage to get the new header’s id (report), probably for aync issues. Any other way to achieve this behaviour?

Hi @manu.reeko, that seems like a reasonable request, and I’d be curious to see how many other users also want this functionality as I can imagine this being very useful. Mind opening a feature request here: Sign in to GitHub · GitHub

That way we can see how desired this feature is via :+1: on the post and prioritize accordingly.

Hi @Nico yes, I can open a request on Github np.

By the way, I found a solution that works for now, and it’s pretty simple. By merging solution for other issues, I manage to change slightly the javascript code in https://discuss.streamlit.io/t/jump-to-section-of-components-html/34180/4, defining a scroll_to function, as follows

def scroll_to(element_id):
    components.html(f'''
        <script>
            var element = window.parent.document.getElementById("{element_id}");
            element.scrollIntoView({{behavior: 'smooth'}});
        </script>
    '''.encode())

The important change consists in calling getElementById on the window.parent.document, and not directly on document. I’m not super expert in Streamlit, and it took my a while to realize that components.html creates a new iframe (afaiu), and calling just document.getElementById would miss any element defined in the iframe parent container html. Of course window.parent.document.getElementById solves the issue, and works like a charm.

I’m glad to hear you were able to find a working solution!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.