Skip to content

Instantly share code, notes, and snippets.

@skannan-maf
Last active February 23, 2025 15:25
Show Gist options
  • Save skannan-maf/e978d3b9cec6ba7b3c826a3bbae90cc5 to your computer and use it in GitHub Desktop.
Save skannan-maf/e978d3b9cec6ba7b3c826a3bbae90cc5 to your computer and use it in GitHub Desktop.
Streamlit: Scroll the browser to the screen where the enclosed streamlit code (within the "with" block) executes
from contextlib import contextmanager
import re
@contextmanager
def streamlit_focus(tab_id, snippet_id):
'''
This is a context manager that will focus the widget with the given widget_key
'''
def make_valid_identifier_string(text: str, char_prefix='A') -> str:
"""
Cleans a string so that it remains alphanumeric with underscores,
and ensures it starts with a letter.
This ensures the resulting string can be used as a valid identifier.
"""
text = re.sub(r'[^a-zA-Z0-9_]', '', text) # Keep only alphanumeric and underscores
if text and not text[0].isalpha():
text = char_prefix + text # Ensure it starts with a letter
return text
tab_id = make_valid_identifier_string(tab_id)
snippet_id = make_valid_identifier_string(snippet_id)
# HEADER: Start a new div
st.markdown('<div id="focus-section-{tab_id}-{snippet_id}"></div>'.format(tab_id = tab_id, snippet_id = snippet_id),
unsafe_allow_html=True)
yield
# FOOTER: Shift the focus to the new div
html('''
<script>
// Time of creation of this script = {now}.
// The time changes everytime and hence would force streamlit to execute JS function
function scrollToMySection_{tab_id}_{snippet_id}() {{
var element = window.parent.document.getElementById("focus-section-{tab_id}-{snippet_id}");
if (element) {{
element.scrollIntoView({{ behavior: "smooth" }});
}} else {{
setTimeout(scrollToMySection, 100);
}}
}}
scrollToMySection_{tab_id}_{snippet_id}();
</script>
'''.format(now=time.time(), tab_id=tab_id, snippet_id=snippet_id),
height=0
)
return
def focus_here(tab_id, snippet_id):
with streamlit_focus(tab_id, snippet_id):
st.empty()
return
#
# Usage:
# focus_here('main_page', 'submit_button')
# st.write('Begin output for submit_button')
# ........
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment