I am trying to reload current page with different url hash, but it doesn't work as expected.
(Clarification how I want it to work: Reload the page and then scroll to the new hash.)
Approach #1:
window.location.hash = "#" + newhash;
Only scrolls to this anchor without reloading the page.
Approach #2:
window.location.hash = "#" + newhash;
window.location.reload(true);
Kinda works but it first scrolls to the anchor, then reloads the page, then scrolls to the anchor again.
Approach #3:
window.location.href = window.location.pathname + window.location.search + "&random=" + Math.round(Math.random()*100000) + "#" + newhash;
Works but I would rather not add random garbage to the url.
Is there a better solution?
I had a JQuery function that fired on
$(document).ready()
which detected if there was a hash appended to the URL in my case, so I kept that function the same and then just used a force reload whenever a hash change was detected:Then my other function -
In my case, it was fine for UX -- might not be good for others.
Another option is to remove the hash and store it in session storage to be retrieved on reload:
and then on top of your page you can have the following code:
It should be expected that #foo will scroll to the anchor of the id, "foo". If you want to use approach #1 and have it reload, this approach might work.
Remove the anchor you're going to navigate to, then use approach #2? Since there's no anchor, setting the hash shouldn't scroll the page.