Reload page when changing hash.
I have a simple one-page site with several 'pages' on it. These pages are in one wide container which scrolls when you choose one. I have added a hash to the URL so that you can locate to specific pages directly. This just sets the style.left attribute when it matches a hash in a switch statement.
The problem is that when I change the hash value in the URL. For example, changing it from Home.html#Web to Home.html#Photos. When doing this, the page doesn't reload so the Setup function I've created that check for the hash isn't called and the page just remains where it is.
Any ideas for a way to force the page to reload? Or a better solution?
Thanks,
Andy
Don't reload the page. Instead, set up a onhashchange event handler, and adjust the left value from there:
window.onhashchange = function() {
// do stuff
}
Otherwise, why using hash links instead of regular links? In any case, if you really want to reload, just put window.location.reload() inside the onhashchange handler...
I had a JQuery function that fired on $('body').on('click', '.subcategory-link', function () { }); which detected if there was a hash appended to the URL in my case, so I kept that function the same and then just used a force reload whenever a hash change was detected:
below i write the code pls try this one it wrok from me charm.
$(document).ready(function() {
$('body').on('click', '.subcategory-link', function () { var data = $(this).attr('href');
alert($(this).attr('href'));
window.location.reload();
});
});
Related
On the footer of the website I'm working on, I have links to different pages, and in one case, 2 links to the same page with a different hash in the url ,like this :
<a href="http://example.com/mypage#test>Test</a>
<a href="http://example.com/mypage#test2>Test2</a>
These hashes are not true anchors, they reflect some actions the user takes (namely showing/hiding some content).
If I come from another page, I navigate without any problem. However, if I am already on "mypage", then the hash changes, but nothing happens. The browser detects and anchor change and thus tries to navigate to the anchor.
That's fair enough, but I want my user to be actually redirected to "http://example.com/mypage#test2", as if he copy-pasted it himself in the address bar. How can I achieve that ?
I could use the hashchange event but it would make it complicated to manage the rest of the javascript, so I wonder if there is a simpler way to do it.
You have a very simple solution if you are using jQuery:
$(window).on('hashchange', function() {
//code
});
Check out this: On - window.location.hash - Change?
Also this MDN documentation.
Use the location.hash property of the window object to find out what the anchor is. To detect a change in the hash, with plain javascript, just use the onhashchange event.
window.onhashchange = new function() {
window.location.replace("http://example.com/mypage" + window.location.hash);
});
I have a menu that loads a new html file in a div. The loading is done by a click event attached to the menu's <a> tags. The loading works well and I add the new load to the history by constructing a new href with a hash tag.
But when I use the back button, the URL is updated correct in the browsers address field, but the page is never loaded. If I focus the address field and press enter it loads.
This is the javascript located in the mypage.html header.
<script type="text/javascript">
$(document).ready(function() {
// replace menu link click
$(".right-menu a").live('click', function(ev) {
ev.preventDefault();
ev.stopPropagation();
window.location.href = $(this).attr('href');
$("#content-right").load('mypage'+window.location.hash.substring(1)+'.html');
return false;
});
// If page loads, load the content area according to the hash.
var hrtag = window.location.hash.substring(1);
if(hrtag=="")
hrtag='about';
$("#content-right").load('mypage'+hrtag+'.html');
window.location.hash = hrtag;
});
</script>
This is the menu
<ul class="right-menu">
<li>About</li>
<li>Screens</li>
<li>License</li>
<li>Download</li>
<li>Donate</li>
</ul>
If I load the page as mypage.html, the javascript will append the hash #about and load the div id "content-right" with mypageabout.html
If I click the menu, for example download, it will load the div id "content-right" with mypagedownload.html
In both cases, the window.location will be set to the hash version of the page, mypage.html#about and mypage.html#download to register them in the history.
If i click the menu in the following order; license, about, screens and then click the browser's back button, the address field will show; mypage.html#about, mypage.html#license but it will NOT load the pages!?!
The URLs are obviously in the history, but they don't load.
Any clue to what might be wrong here?
// Thanks
EDIT - The solution
Thanks to Andres Gallo's article I came up with this solution:
<script type="text/javascript">
$(document).ready(function() {
// Make sure the page always load #about
LoadIDWithURL('#content-right','myPageAbout.html');
window.addEventListener('hashchange',function() {
if (window.location.hash != "") {
// We have a hash, use it!
LoadIDWithURL('#content-right','MyPage'+window.location.hash.substring(1)+'.html');
} else {
// We do not have a hash, force page reload!
window.history.go(0);
}
});
});
// Load the targetID with the URL loadURL.
function LoadIDWithURL(targetID,loadURL) {
$(targetID).load(loadURL);
}
</script>
I wrote a very detailed article on this exact topic. It explains how to build exactly what you are trying to do.
Furthermore my article also explains how you can pass parameters in your links to have javascript do special things
Here is a link to the article http://andresgallo.com/2012/06/08/ajaxifying-the-web-the-easy-way/
The best method is to attach your functionality to your hashchanges rather than to you click events. This allows any changes in history to take advantage of your javascript functionalities.
This is normal behaviour when navigating between pages which differ only in their hash. You have two options:
Use the hashchange event, or an emulation of it, to detect when the user changes the hash by navigation back or forward and update the page appropriately
Use the HTML5 history API.
you can try with hashchange
$(function(){
$(window).hashchange(function(){
// some event
})
})
I have a simple javascript/jQuery related question:
I have the following markup in my tumblr blog:
NEXT
The # above changes according to which page the user is on. ie: # is variable, and cannot be static.
With jQuery, I would like to perform an effect (slideUp();, to be specific) before the new link is opened.
Is that possible?
I have tried both .click() and .mousedown(). Doesn't seem to work, since when I click the link, the new page opens up before any effects take place.
I have heard of preventDefault(), but I'd like to shy away from that, for that would mean I must create a separate function to detect the page #, etc. (too much work~)
I recommend against doing that. Just let the user change pages.
However, if you really want to, what you need to do is indeed preventDefault (explicitly, or by returning false from your handler), do the slideUp, and then in the slideUp completion function, trigger the change in URL.
Like this:
$("a.pagination").click(function() {
// Grab the link's href
var href = this.href;
// Slide up the content you want to slide up
$("some_selector_here").slideUp(function() {
// Slide is finished, navigate
location.href = href;
});
// Prevent the default action of the link
return false;
});
You just need to defer changing of page's url:
$('.pagination').click(function(){
var link = this;
$('.some-other-element').slideUp(500, function(){
location.href = this.getAttribute('href');
});
return false;
});
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 sends 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
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
I would still recommend just monitoring the hash though.
Simple like that
#hardcore
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:
myanchor2
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:
example1
example2
example3
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):
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
click me
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
Magic
Hope this helps anyone!
Try this by adding simple question mark:
Going to Anchor2 with Refresh
I have a page with two tabs that I want to be able to switch with Javascript, but also set the anchor (e.g. page.html#tab1) in the URL for bookmarking/linking.
By default the tab contents are in two divs, one below the other, and the anchor tag will scroll to the correct one, with JS disabled.
With JS enabled, CSS classes are applied to make them act as tabs. Each tab links to each anchor, but when you click to switch tabs, the page scrolls to the tab. If I return false from the onclick function then the URL doesn't change to include the anchor.
How do I make the browser URL change to page.html#tab1 but not scroll to #tab1 ??
I've played with this for a while, because I initially didn't believe you (I use the jQuery history plugin to get similar behavior).
And I'm stumped. I don't think you can. What you could do, as a workaround, is use javascript to set the hash to something DIFFERENT from what is actually on the page. And then use javascript upon load to read the hash and populate the correct content. I do this on my site. So in that scenario, users without javascript would be scrolled, users with javascript would keep the history chain, and it only gets wacky when people without send links to people with (or vice-versa).
A quick hack:
var thehash = e.target.hash;
$(thehash).prop('id',thehash.substr(1)+'-noscroll');
window.location.hash = e.target.hash;
$(thehash+'-noscroll').prop('id',thehash.substr(1));
This changes the id of the html element before and after changing the hash of the url. Works for me, but might as well break something. This prevents the browser from scrolling on a hash change, since there is not html element with that id in between.
Could you have some Javascript that changed the anchor names, set window.location.hash, and then changed the anchor names back?
(I've confirmed that andynormancx is right, and setting window.location.hash scrolls the view, but I'm too lazy to test if creating an anchor in the DOM to window.location.hash also scrolls.)
var Namespace = {
var timer, scroll;
}
// Onclick
Namespace.scroll = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
Namespace.timer = setInterval(function() { scrollTo(0, Namespace.scroll) }, 100);
location.hash = this.href;
clearInterval(Namespace.timer);
I found a nice solution here: http://lea.verou.me/2011/05/change-url-hash-without-page-jump/
Use a preventDefault on for example a click event
$('a').click((event) => {
event.preventDefault();
let hash = $(event.target).attr('href');
history.pushState(null, null, hash);
// The url now has a hash but the page won't jump to the given anchor
// .. handle the rest (an easing scroll for example)
});
window.location.hash = 'tab1';
might work.