Fire a callback when `html.Img` is clicked

Is there a way to make an html.Img item clickable such that when it is clicked, a callback is fired off?

Sure, the html.Img component has an n_clicks prop. You can use it like this:

from dash import Dash, html, Input, Output

app = Dash(__name__)

webb_deep_field = "https://user-images.githubusercontent.com/72614349/192781103-2ca62422-2204-41ab-9480-a730fc4e28d7.png"

app.layout = html.Div(
    [html.Img(id="img", src=webb_deep_field, n_clicks=0), html.Div(id="output")]
)


@app.callback(
    Output("output", "children"),
    Input("img", "n_clicks"),
)
def update(n):
    if n > 0:
        return f"Image clicked on {n} times"


if __name__ == "__main__":
    app.run_server(debug=True)



4 Likes

@AnnMarieW Thanks a lot! That’s exactly what I was looking for.

1 Like