URI Fragment identifier to scroll to an element that is generated with JavaScript

755 views Asked by At

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.

1

There are 1 answers

1
Sean Vieira On

Assuming you know the dynamic ID, just change the hash using history.replaceState once the UI-building JS has finished running:

const staticText = Array(1000).join("-").split("-").map(() => "This is some text for spacing purposes.").join("\n");
canvas.innerHTML = staticText + "<div id='dynamic-id'>Hello from JS!</div>"

history.replaceState({}, "Title", "#dynamic-id");
:target {
  background-color: yellow;
  font-weight: bold;
  color: red;
  font-size: 3em;
}
#canvas { white-space: pre-wrap; }
<div id="canvas">Just some unvarnished HTML</div>