Javascript: How to Force a Page Reload and Jump to a Specified Anchor Name in the Process CodeUnit 30 JAN 2012

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';

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


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.

  • François Wognum

    Was just looking for this, as you say, nifty way to hop back and jump to a certain archor. Nice one, thanks!