Create animation for messages when button is clicked

Summary

I am attempting to create a button that, when clicked, will display a message for a specified period of time and then gradually fade away and disappear once the timer has run out.

Steps to reproduce

Code snippet:

import streamlit as st
from time import sleep

if st.button("Hello"):

    with st.empty():
        for second in range(2):
            st.success(f"Success - ⏳ {second+1}", icon="βœ…")
            sleep(1)

    # Add CSS to fade out the message
    st.markdown("""
        <style>
            @keyframes fadeOut {
                from { opacity: 1; }
                to { opacity: 0; }
            }
            .stAlert {
                animation: fadeOut 2s ease;
            }
        </style>
    """, unsafe_allow_html=True)

Expected behavior:

The success message should fade out smoothly and disappear.

Actual behavior:

The success message fades out but does not disappear.

Other info

I tried various approaches like messing with st.empty or using a style.css file but have been unable to find a solution. Thank you in advance :slight_smile:

I was trying to achieve something similar, and I found a solution that seems to work. Moreover, without using sleep after the markdown, you can press the button again before the fade out animation is over, and it will restart again from the beginning

import streamlit as st
import time

ok_message = None
ok_css = None
def fade_out(message):
    global ok_message, ok_css
    ok_message.empty()
    ok_css.empty()
    ok_css.markdown("""
        <style>
            .stAlert {
                opacity: 1;
                anmation: None;
            }
        </style>""", unsafe_allow_html=True)
    time.sleep(0.1)
    ok_message.success(message)
    ok_css.markdown("""
        <style>
            @keyframes fadeOut {
                from { opacity: 1; }
                to { opacity: 0; }
            }
            .stAlert {  
                animation-name: fadeOut;
                animation-duration:  2s;
                opacity: 0;
            }
        </style>
    """, unsafe_allow_html=True)

button1 = st.button("Hello")
ok_message = st.empty()
ok_css = st.empty()
if button1:
    fade_out("Success")

1 Like

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