Javascript reload the page with hash value
JavascriptJqueryJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
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 - Javascript
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 - Javascript
This is really an old post, I would still try and answer with right combination of answers.
location.reload()
andlocation.reload(true)
works like F5 on browser. This will post all the form data back to the server if previously load had done it.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 doinglocation.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.
Solution 4 - Javascript
var loc = location.hash;
location.hash = " ";
location.hash = loc;
Solution 5 - Javascript
Try this
var urlString=window.location.href;
var url=urlString.split("#")[0];
window.location.href = url + "#mypara";
Solution 6 - Javascript
This worked for me:
var tabValue = document.URL;
window.location = tabValue.substring(0, tabValue.lastIndexOf("#"));
window.location.hash = "#tabs-3"; //Whatever is your hash value
location.reload();
Solution 7 - Javascript
This worked for me
$('body').on('click', '.className', function () {
var data = $(this).attr('href');
alert(data);
window.location.reload();
});
Solution 8 - Javascript
This work for me
window.location.href = baseUrl + "#/m/team";
location.reload();