Black Lives Matter. Please consider donating to Black Girls Code today.

Anchor links not working on page load

I have a single-page app where i use anchor links to scroll to the desired sections. If i load the “frontpage” of the app, i.e. without any anchors, and click the links, everything works as intended. However, i am unable to “deep link”, i.e. go directly to an anchor, without loading the page first. Here is a MWE,

import dash
import dash_html_components as html

app = dash.Dash()
app.layout = html.Div([html.P("Hello world."), html.A("To the end", href="#end")] + [html.Br()]*100 +
                      [html.P("Goodbye world", id="end")])

if __name__ == '__main__':
    app.run_server()

If you to run the code, go to http://127.0.0.1:8050/ and click the link, the page will scroll to the bottom. However, if you just open the link http://127.0.0.1:8050/#end, it will not. Is there any way to achieve this behavior?

there aren’t any workarounds that we’re aware of. our current hypothesis is that the page loads too slow for the browser to automatically perform its page scroll-on-page-load functionality. we believe that we’ll need to solve this in dash’s front-end with custom page scrolling-after-render.

Ah, that makes sense. Too bad. I guess i will just have to hack it for now. If others encounter the issue, i have put the hack in my dash-extensions package,

pip install dash-extensions==0.0.7

The example from before would then look like this,

import dash
import dash_html_components as html
from dash_extensions.snippets import fix_page_load_anchor_issue

app = dash.Dash()
app.layout = html.Div([html.P("Hello world."), html.A("To the end", href="#end")] + [html.Br()]*100 +
                      [html.P("Goodbye world", id="end")] + fix_page_load_anchor_issue(app))

if __name__ == '__main__':
    app.run_server()
2 Likes