Anchor names are a great little browser extra that allows you to quickly jump to different sections on a web page courtesy of a handy little # declaration in the page URL. However, these do sometimes get in the way, for instance you want to reload a page’s contents via Javascript, but at the same time want to stay on the section of the page which the user was currently at.

If you specify the anchor name in the URL and to a location equals or reload like you normally would, then unfortunately for you the page won’t reload and will simply jump to the newly specified anchor name – definitely not the behaviour that we want! So how do we get around this then and force the page to first refresh, and then jump to the specified anchor name?

Well actually the answer is pretty simple really. We make use of the optional value of the window.location.reload function to force an actual reload (i.e. ignore the browser cache)!

In practice, first set the current window’s URL (i.e. the page you want to refresh) as the window.location.href value, specifying the anchor name you wish to jump to in the URL. Then call a window.location.reload, specifying true as the function parameter. In code, this would look like:

window.location.href = 'mypagetoreload.htm#jumptosection1';
window.location.reload(true);

And that is that. The page will first hard refresh itself and once refreshed, jump through to the specified section.

Nifty.