Refreshing hash part of URL to trigger scrolling

For the admin pages of the "Unified Database" we've built, I recently wrote a simple jump link generator using javascript/jquery. It basically looks up all H2 headings on the page, inserts an anchor link inside and adds a corresponding jump link to a navigation box in the side menu.

This worked as intended, but a problem was that, since the anchor links don't exist initially when the page loads but only after the javascript code has executed, the browser doesn't find a target to scroll to when you visit or reload the page with a URL looking like www.example.com/page#section3. Luckily there was a trivial solution to this:

createJumpLinks();
window.location.hash=window.location.hash;

Since the hash part of the URL can be changed using javascript, and since doing so triggers a scrolling of the browser window, "refreshing" the hash like this gives us the desired effect of the page being scrolled to the right position onload.

Add new comment