I generate HTML with JavaScript code when the page loads. The problem is when using URI fragments, like http://example.com/index.html#special-id
, the browser doesn't automatically scroll to the element with the id special-id
. At least that doesn't happen in Chrome. I assume this isn't working because #special-id
doesn't exist when the page first loads. Only after the JavaScript is run does it exist.
Is there a way to make this work easily? I could always add JavaScript code to check the URI fragment and scroll to it every time I create a new element with an id
attribute. But that isn't always so easy in my situation with code I don't always control. I'd also rather not use a MutationObserver
if possible.
Assuming you know the dynamic ID, just change the hash using
history.replaceState
once the UI-building JS has finished running: