html.Button - Adding a click event

Hey,

I’m trying to make a ‘Reset Filters’ button for my dashboard. I’m really struggling to get the html.Button to have any interactive capability whatsoever. Is there a way to make this work?

I guess I could use the dcc.Checklist with a single box, but the UI isn’t as intuitive as a button.

Thanks,

Rich

2 Likes

Literally just came across this other thread which provides an answer:

https://community.plotly.com/t/more-sliders-help-with-button-callback-example/?source_topic_id=5073

For future readers:

app.layout = html.Button('Click Me', id='my-button')

@app.callback(Output(...), [Input('my-button', 'n_clicks')])
def on_click(number_of_times_button_has_clicked):
     ...
1 Like

It appears that this solution will automatically trigger the click event on the button when the app starts up. This wouldn’t work for me, as I’m trying to write an app where clicking the button would trigger an expensive computation, and I don’t want to force the user to have to wait for that to finish whenever the app starts up.

Is there a way to do this that won’t trigger the event on startup?

1 Like

Correct me if I’m wrong, but the n_clicks parameter will initialise at 0. You could test if n_clicks > 0 and then trigger the computation?

5 Likes

n_click is initially None in the inital callback and on the first click is set to 1. Zero is never the value of n_click till initialized by you.

@callback([.......])
def update_something():
if n_clicks!=None:...
It will prevent the event to trigger on startup!

2 Likes

These incomplete examples are not very helpful.

1 Like

I finally find a way out…

You just have to create a clientside callback…

app.layout = html.Div([
dcc.Textarea(id=“value”, value=“Value”),
dbc.Button(id=“copy-clipboard”, children=“Copy to clipboard”)
])

app.clientside_callback(
“”"
function(n_clicks) {
var copyText = document.getElementById(“value”);
copyText.select();
copyText.setSelectionRange(0, 99999)
document.execCommand(“copy”);
return n_clicks;
}
“”",
Output(“copy-clipboard”, “n_clicks”),
Input(“copy-clipboard”, “n_clicks”)
)

Enjoy!!