Force page reload with html anchors (#) - HTML & JS
Say I'm on a page called /example#myanchor1
where myanchor
is an anchor in the page.
I'd like to link to /example#myanchor2
, but force the page to reload while doing so.
The reason is that I run js to detect the anchor from the url at the page load. The problem (normally expected behavior) here though, is that the browser just sen开发者_运维百科ds me to that specific anchor on the page without reloading the page.
How would I go about doing so? JS is OK.
I would suggest monitoring the anchor in the URL to avoid a reload, that's pretty much the point of using anchors for control-flow. But still here goes. I'd say the easiest way to force a reload using a simple anchor-link would be to use
<a href="?dummy=$random#myanchor2"></a>
where in place of $random
insert a random number (assuming "dummy" is not interpreted server side). I'm sure there's a way to reload the page after setting the anchor, but it's probably more difficult then simply reacting to the anchor being set and do the stuff you need at that point.
Then again, if you reload the page this way, you can just put myanchor2
as a query parameter instead, and render your stuff server side.
Edit
Note that the link above will reload in all circumstances, if you only need to reload if you're not already on the page, you need to have the dummy variable be more predictable, like so
<a href="?dummy=myanchor2#myanchor2"></a>
I would still recommend just monitoring the hash though.
Simple like that
<a href="#hardcore" onclick="location.reload()">#hardcore</a>
an example
Another way to do that is to set the url, and use window.location.reload()
to force the reload.
<a href="/example#myanchor2"
onclick="setTimeout(location.reload.bind(location), 1)">
</a>
Basically, the setTimeout
delays the reload. As there is no return false
in the onclick, the href
is performed. The url is then changed by the href
and only after that is the page reloaded.
No need for jQuery, and it is trivial.
My favorite solution, inspired by another answer is:
<a href="#myanchor2" onclick="location.hash='myanchor2'; location.reload();">myanchor2</a>
href
link will not be followed so you can use your own preference, for example: ""
or "#"
.
Even though I like the accepted answer I find this more elegant as it doesn't introduce a foreign parameter. And both @Qwerty's and @Stilltorik's answers were causing the hash to disappear after reload for me.
What's the point of using client-side JS if you're going to keep reloading the page all the time anyways? It might be a better idea to monitor the hash for changes even when the page is not reloading.
This page has a hash monitor library and a jQuery plugin to go with it.
If you really want to reload the page, why not use a query string (?foo) instead of a hash?
Another option that hasn't been mentioned yet is to bind event listeners (using jQuery for example) to the links that you care about (might be all of them, might not be) and get the listener to call whatever function you use.
Edit after comment
For example, you might have this code in your HTML:
<a href="example#myanchor1" class="myHash">example1</a>
<a href="example#myanchor2" class="myHash">example2</a>
<a href="example#myanchor3" class="myHash">example3</a>
Then, you could add the following code to bind and respond to the links:
<script type="text/javascript">
$('a.myHash').click(function(e) {
e.preventDefault(); // Prevent the browser from handling the link normally, this stops the page from jumping around. Remove this line if you do want it to jump to the anchor as normal.
var linkHref = $(this).attr('href'); // Grab the URL from the link
if (linkHref.indexOf("#") != -1) { // Check that there's a # character
var hash = linkHref.substr(linkHref.indexOf("#") + 1); // Assign the hash to a variable (it will contain "myanchor1" etc
myFunctionThatDoesStuffWithTheHash(hash); // Call whatever javascript you use when the page loads and pass the hash to it
alert(hash); // Just for fun.
}
});
</script>
Note that I'm using the jQuery class selector to select the links I want to 'monitor', but you can use whatever selector you want.
Depending on how your existing code works, you may need to either modify how/what you pass to it (perhaps you will need to build a full URL including the new hash and pass that across - eg. http://www.example.com/example#myanchor1), or modify the existing code to accept what you pass to it from you new code.
Here's something like what I did (where "anc" isn't used for anything else):
<a href="/example?anc=myanchor2"></a>
And onload:
window.onload = function() {
var hash = document.location.hash.substring(1);
if (hash.length == 0) {
var anc = getURLParameter("anc");
if (anc != null) {
hash = document.location.hash = anc;
}
}
}
The getURLParameter function is from here
If you need to reload the page using the same anchor and expect the browser to return to that anchor, it won't. It will return to the user's previous scroll position.
Setting a random anchor, overwriting it and then reloading seems to fix it. Not entirely sure why.
var hash = window.location.hash;
window.location.hash = Math.random();
window.location.hash = hash;
window.location.reload();
Try this its help for me
<a onclick="location.href='link.html'">click me</a>
In your anchor tag instead of
<a href="link.html">click me </a>
As suggested in another answer, monitoring the hash is also an option. I ended up solving it like this so it required minimal code changes. If I had asked the original question, I believe I would have loved to see this option fully explained.
The added benefit is that it allows for additional code for either of the situations (hash changed or page loaded). It also allows you to call the hash change code manually with a custom hash. I used jQuery because it makes the hash change detection a piece of cake.
Here goes!
Move all the code that fires when a hash is detected into a separate independent function:
function openHash(hash) {
// hashy code goes here
return false; // optional: prevents triggering href for onclick calls
}
Then detect your hash for both scenarios like so:
// page load
$(function () {
if(typeof location.hash != typeof undefined) {
// here you can add additional code to trigger only on page load
openHash(location.hash);
}
});
// hash change
$(window).on('hashchange', function() {
// here you can add additional code to trigger only on hash change
openHash(location.hash);
});
And you can also call the code manually now like
<a href="#" onclick="openHash('super-custom-hash')">Magic</a>
Hope this helps anyone!
Try this by adding simple question mark:
<a href="?#anchor2">Going to Anchor2 with Refresh</a>
精彩评论