Scroll to page section that is being rendered

Hi,

In my streamlit app, there are some buttons in the top. When I click these, a certain section of the page changes. I want the browser to scroll to that section upon button click.

Right now, I tried this. But not working.

Just before the interesting section:

st.markdown('<div id="my-section"></div>', unsafe_allow_html=True)

Just after the interesting section:

from streamlit.components.v1 import html as scv1html

scv1html(
    """
    <script>
        function scrollToElement() {
            var target = window.parent.document.getElementById('my-section');
            if (target) {
                target.scrollIntoView({behavior: 'smooth'});
            } else {
                // Retry after 100 milliseconds if the element is not found
                setTimeout(scrollToElement, 100);
            }
        }
        scrollToElement();
    </script>
    """,
    height=0,  # Set height to 0 since we don't need to display anything
)

In spite of this, nothing happens.

The Developer tools says that scrollIntoView is being called from Null… Though there is an explicit check in Javascript…

Any help greatly appreciated. Thanks!

I made it work - including force running the JS when buttons are clicked on the page.

I still dont know the main reason why the snippet in the original post did not work. Perhaps it is the single-quote thing. I switched to double-quote now.

Also, I added a comment in the JS code that is expanded to current time. This forces streamlit to run the JS code for every change. And that simply works! Pure gold!

Here is the snippet for anyone interested!

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