Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 334
Jonas T Avatar asked May 16 '12 05:05

Jonas T


People also ask

How do I reload a page in JavaScript?

reload() method reloads the current web page. The method gives the exact same result as pressing the RELOAD button in your browser. The JavaScript reload page method loads the page from the cache by default. If the forceGet property is set to true, the page is reloaded from the server.

How do you reload an object in JavaScript?

In JavaScript, the reload() method is used to reload a webpage. It is similar to the refresh button of the browser. This method does not return any value.

What is location reload ()?

The location. reload() method reloads the current URL, like the Refresh button.

How do you call a function when a page reloads?

You need to call myFunction() when the page is loaded. window. onload = myFunction; If you only want to run it when the page is reloaded, not when it's loaded for the first time, you could use sessionStorage to pass this information.


2 Answers

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.

like image 184
Derek 朕會功夫 Avatar answered Oct 21 '22 13:10

Derek 朕會功夫


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(); 
like image 34
ug_ Avatar answered Oct 21 '22 12:10

ug_