Automatically scroll down page to graph when ready

I have an app created with Dash and bootstrap components which dynamically show some plots after the user has entered some inputs. Graphs are created only after the user presses on a “generate” button so they don’t exist at first loading.

Since the page on mobile is quite long I would like to automatically scroll to the first plot as soon as it is created: this could take few seconds depending on the server load. I’ve achieved this using a clientside callback waiting for the element to appear in the page.

app.clientside_callback(
    """
    function scrollToBottom(clicks, elementid) {
    var counter = 30;
    var checkExist = setInterval(function() {
          counter--
          if (document.getElementById(elementid) != null || counter === 0) {
            clearInterval(checkExist);
            document.getElementById(elementid).scrollIntoView({behavior: "smooth",
                                                            block: "start",
                                                            inline: "nearest"})
          }
        }, 100);
    }
    """,
    Output('garbage-output-0', 'children'), # just needed to have an output
    [Input("generate-button", "n_clicks")], # the trigger for generating the plot
    [State('temp-fig-card', 'id')], # the plot itself that I want to scroll to
    prevent_initial_call=True
)

However I have the following issues

  • it behaves randomly (sometimes it scroll, sometimes it does not, sometimes it only scrolls half the page)
  • I have to do a kind of loop to wait for the element to appear
  • this breaks easily if the generation of the plot takes too long (for other reasons)

Is there any better solution?

Hi @guidocioni

Could be dcc.Location an option ?

https://dash.plotly.com/dash-core-components/location

You mean assigning the figure a url, maybe with hash, and then having a normal callback triggered by the “generate” button which navigates to the link of the figure, thus scrolling down?
How would you do that exactly?

Yes!

I don’t know :woozy_face: