Hover over selectbox: display current selection text

Is there a way to hover over a streamlit selectbox component and display the currently selected item in a tooltip?

This is useful when the currently selected item’s text is too long.

An example:

selectbox_options = ['extremely long textextremely long textextremely long textextremely long textextremely long textextremely long textextremely long textextremely long text', 'b', 'c']
with st.sidebar.header("Sidebar"):
    selected_kb = st.selectbox("Choose something", selectbox_options)

My attempt at using javascript to add a title to my selectbox based on current selection:

script = """
    <script>
        

        const updateTooltip = () => {
            console.log("Update tool tip triggered!")
           const selectbox = document.querySelector(".stSelectbox");
        selectboxTextDiv = document.querySelector("#root > div:nth-child(1) > div.withScreencast > div > div > div > section.st-emotion-cache-1cypcdb.eczjsme11 > div.st-emotion-cache-6qob1r.eczjsme3 > div.st-emotion-cache-16txtl3.eczjsme4 > div > div > div > div > div > div > div > div.st-bf.st-bg.st-bz.st-c0.st-c1.st-b4.st-c2.st-c3.st-bh.st-c4.st-c5.st-c6.st-c7 > div.st-c8.st-bf.st-c9.st-ca.st-cb.st-bh.st-cc.st-cd.st-ce")
        selectbox.title = selectboxTextDiv.textContent
        };

        // Initial update
        updateTooltip();

        // Add event listener for change event
        selectboxTextDiv.addEventListener("change", updateTooltip);
    </script>
"""
components.html(script)

which errors out:

Update tool tip triggered!
about:srcdoc:9 Uncaught TypeError: Cannot read properties of null (reading 'textContent')
    at updateTooltip (about:srcdoc:9:44)
    at about:srcdoc:13:9

If I manually add the title field to the selectbox div using chrome dev tools, the hover indeed works how I want it to. But idk how to make it work with streamlit…

I’m using python 3.11 and streamlit 1.29

This is as close as I could get but the behavior is inconsistent even though my callback is invoked (I see the python print statement everytime, but not the console.log statements). I don’t understand why it doesn’t update the title of the selectbox everytime the value is changed? It seems to update it when I change the selectbox value twice or thrice. I don’t fully understand what I’m seeing. Here’s the code:

import streamlit as st
import streamlit.components.v1 as components

selectbox_options = ['extremely long textextremely long textextremely long textextremely long textextremely long textextremely long textextremely long textextremely long text', 'b', 'c']

# Custom HTML and JavaScript to add tooltips to the selectbox
script = \
"""
<script>
    console.log("I'm in the script!!!");
    selectbox = window.parent.document.querySelector(".stSelectbox");
    console.log("selectbox", selectbox);
    selectboxTextDiv = window.parent.document.querySelector("#root > div:nth-child(1) > div.withScreencast > div > div > div > section.st-emotion-cache-1cypcdb.eczjsme11 > div.st-emotion-cache-6qob1r.eczjsme3 > div.st-emotion-cache-16txtl3.eczjsme4 > div > div > div > div > div > div > div > div > div");
    console.log("selectboxTextDiv", selectboxTextDiv);
    selectbox.title = selectboxTextDiv.textContent;
</script>
"""

# Display the script
def add_title_to_selectbox():
    print("callback invoked")
    components.html(script)

# Streamlit components
with st.sidebar.header("Sidebar"):
    selected_kb = st.selectbox("Choose something", selectbox_options, on_change=add_title_to_selectbox)

Perhaps you may be interested in finding the solution using Streamlit toast.
ezgif.com-video-to-gif-converter (1)

import streamlit as st
import streamlit.components.v1 as components
selectbox_options = ['extremely long textextremely long textextremely long textextremely long textextremely long textextremely long textextremely long textextremely long text', 'b', 'c']
selected_kb = st.sidebar.selectbox("**Choose something**", selectbox_options)
def _customize_css_style():
    # Note padding is top right bottom left
    st.markdown(
        """
        <style>
                        
            div[data-testid=toastContainer] {
                top:50px;
                padding: 10px 10px 100px 50px;
                align-items: center;
            }
           
            div[data-testid=stToast] {
                padding: 20px 10px 40px 10px;
                width: 40%;
            }
             
            [data-testid=toastContainer] [data-testid=stMarkdownContainer] > p {
                font-size: 20px; font-style: normal; font-weight: 400;
                foreground-color: #ffffff;
            }

        </style>
        """, unsafe_allow_html=True
    )
    
_customize_css_style()
st.toast('Selected: '+selected_kb)

Thank you for responding! I really appreciate it, but a toast really doesn’t really feel right for this.

It’s important for the full text to appear on a hover, and only if the user wants to see it (maybe they don’t care to read the very long string, or they already read it when selecting). But after they’ve selected it, I want to give them a way to quickly see what they have selected :frowning:

I haven’t used st.toast yet btw, so I’m also not fully sure if we can control where the toast appears. In your gif, it appears in the middle of the screen, but my work will all be in the sidebar.

Anyway, I really feel like there must be a way to do this, if we can just find the right javascript function to use as a callback maybe?

I’m all ears to other ideas/possible solutions.

:warning: Unfortunately st.toast cannot be called directly on the sidebar.

:white_check_mark: Another way to show the user the option they selected would be by using the following code:

import streamlit as st
from streamlit.components.v1 import html #Necessary for run javascript code
selectbox_options = ['extremely long textextremely long textextremely long textextremely long textextremely long textextremely long textextremely long textextremely long text', 'b', 'c']
def update_tooltip(text):
    return f"""<script>
        document.addEventListener('DOMContentLoaded', function() {{
            var parentWindow = window.parent;
            var tooltiptextElement = parentWindow.document.querySelector('.tooltiptext');            
            tooltiptextElement.textContent = '{text}';
        }});
    </script>
"""
 
with st.sidebar:
    st.markdown("""
        <div class="tooltip" id="myTooltip">
        <!-- Tooltip text -->
            <span class="tooltiptext">This is a simple tooltip</span>
        </div>
    """, unsafe_allow_html=True)

    selected_kb = st.selectbox("**Choose something 👇**", selectbox_options)
    if selected_kb:
        st.markdown(""" <style>
        /* Tooltip container */
        .tooltip {
            position: relative;
            display: inline-block;
            text-align: center;
            padding:4px;
            cursor: pointer;
        }

        /* Tooltip text */
        .tooltiptext {
            width: 200px;
            background-color: #555;
            color: #fff;
            border-radius: 6px;
            position: absolute;
            white-space: nowrap; /* Prevents the text from wrapping */
            overflow: hidden; /* Hides the overflowing text */
            text-overflow: ellipsis; /* Adds ellipsis (...) for overflowed text */
            z-index: 1;
            bottom: 125%;
            opacity: 1;
            transition: opacity 0.3s;
        }

        .tooltip:hover .tooltiptext {
            white-space: normal; /* Allow text to wrap */
            overflow: visible; /* Show overflowing text */
            text-overflow: initial; /* Remove ellipsis */
            visibility: visible;
            opacity: 1;
        }
    </style>""", unsafe_allow_html=True)
        html(update_tooltip(selected_kb), height=0)
        st.write("You selected: "+f":red[{selected_kb}]")