Javascript reload the page with hash value

I am trying to refresh the page with this statement in external javascript file after some processes.

window.location.href = window.location.href

It perfectly reload the page but I want to scroll to the specific location after reload. So, I put this on the page.

<a name="uploadImgSection"></a>

And change the javascript to

window.location.href = window.location.href + "#mypara";

This code doesn't reload/refresh the page either

window.location.hash = "#uploadImgSection";
window.location.href = window.location.href;

When I do that, it doesn't reload the page at all. Is there any way I can reload the page with scroll bar position?


Solution 1:

window.location.href += "#mypara";
location.reload();

First add the hash, then reload the page. The hash will remain there, and the page gets reloaded.

Tested, works.


ps: If a hash already exist in the URL, you may want to directly change it via location.hash instead of .href.

Solution 2:

I wanted to update this question because I found that using window.location.href += "#mypara" will keep appending the parameter to the url even if it exists. I have found the better way is to use

window.location.hash = "#mypara"
location.reload();

Solution 3:

This is really an old post, I would still try and answer with right combination of answers.

  1. location.reload() and location.reload(true) works like F5 on browser. This will post all the form data back to the server if previously load had done it.
  2. location.href will not refresh the page until there is a URL change recognized by the browser. change in hash (#paramname) doesn't qualify for URL change and hence just doing location.href+="#paramname" will not work.

So, location.href+="?anything#paramname" should reload the page as a new request as ?anything is change in the URL.