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")
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 on the post and prioritize accordingly.
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.