URL fragment in the browser

Recreating common behavior

When you got to a page with #identifier appended to the end the browser will, after loading the page jump directly to the element with id="identifier".

Formally the part after hash is known as a fragment identifier (specified in rfc3986). And how the client should react to it depends on the specific MIME type. For HTML, it’s bringing that element into view.

In my recent project, I had to recreate that behavior. I couldn’t depend on the browser because I was creating the page content on the fly. It depended on the series of AJAX requests and the initial page didn’t contain the element with the id from the URL hash.

Turns out the behavior is not that complicated to reproduce. Thanks to a nifty DOM method perfectly suited to that task. scrollIntoView. (Although there’s a warning on that page it only matters in the case of using scrollIntoViewOptions. My use case of simply passing true is supported broadly.)

In the end, following bit of code is all that was needed.

const elementId = window.location.hash.slice(1);
const element = document.getElementById(elementId);
if (element) {

.slice(1) is to remove # from the beginning of the string, so to have just the id. In the case where there’s no URL fragment present, it will return empty string. document.getElementById will return null if the element is not found (and there can’t be an element with an empty id).

The only tricky part left was to execute this piece of code at the right time, when the desired element has been added to the page. After finding that place, works perfectly.