Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force a page to reload if all what was changed in url is hash?

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?

like image 592
serg Avatar asked Oct 19 '09 16:10

serg


People also ask

How do I refresh my current URL?

You can use the location. reload() JavaScript method to reload the current URL. This method functions similarly to the browser's Refresh button. The reload() method is the main method responsible for page reloading.

How do I know if a URL has a hash?

The task is to check whether an URL contains or not. This can be done by using the Location hash property in JavaScript. It returns the string which represents the anchor part of a URL including the hash '#' sign.

Can a URL have multiple hash?

To sum up: Only one "#" is allowed in a compliant URL (or URI) as the marker for the URL-fragment. Especially hash signes that are supposed to be in the path (at least from the looks, as there are slashes afterwards) are problematic as they officially terminate the path part.

How do I refresh a page using anchor tag?

After you set the specified URL into location, issue window. location. reload(true) . This will force browser to reload the page.


Video Answer


1 Answers

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.

like image 118
Nickolay Avatar answered Sep 24 '22 02:09

Nickolay