Loading a page from hash on refresh - javascript

So I wrote this piece of JavaScript using the JQuery library. Its functionality is to have the pages load inside of a div instead of an entire page (to make modifying the layout way easier).
I've made it so it successfully saves the 'file URL' in the hash and I've made it so it loads correctly, but I can't for the life of me figure out how to go to that page.
When I try to go to a page with the hash in the name (so for example refreshing a page, or going through a link/URL) it replicates itself (I think) two times inside each other. You can see it happening live at overeten.be and then try to refresh a random page except the main one.
Could someone help me with this problem? Thanks in advance!
$("document").ready(function(){
$('._body').load("pages/default.html");
var locationhash = window.location.hash.replace('#','');
if ((locationhash=='pages/default.html')||(locationhash=='')){
console.log("no page, "+locationhash);
} else{
$('._body').load(window.location.hash);
console.log(locationhash);
}
$('.menubundle a, footer a').on('click', function (e) {
e.preventDefault();
var page = $(this).attr('href');
$('._body').fadeOut(1000,function(){
document.location.hash = page;
$('._body').load(page).fadeIn(1000);
});
});
});

The problem is on this line:
$('._body').load(window.location.hash);
If you inspect window.location.hash, you get this:
window.location.hash
"#pages/over_eten/feit.html"
That URL points to the current page. What you really want is this:
window.location.hash.slice(1) // Skip the first character
"pages/over_eten/feit.html"
On a side note, it seems weird to me that you have two calls to $('._body').load(). The first one seems like it belongs right above console.log('No page...') instead.

Related

Handling url targeted PHP page with custom jQuery loaded content

First I used include('pageName.php'); for every page I wanted to load.
Now I decided to rewrite everything and to load a page in a <div id="page_content"></div> with the jQuery function: $('#page_content').load(pageurl, {access:true});
I hope this is the best practice. Because I want to reduce load time on my web application by not refreshing the whole website with all CSS and JS files but just to refresh content when clicked on a new page.
Currently I am using the following function to load pages into the division and to pushState to history:
//Dynload pages
$("a[rel='dynload']").click(function(e) {
e.preventDefault();
var page = $(this).attr("page");
var pageurl = "pages/" + page + ".php";
$('#page_content').load(pageurl, {access:true});
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',page);
}
//stop refreshing to the page given in
return false;
});
This works perfectly.
I have this button that triggers this function and gives for attribute page="index_content" . The function will load this page to the division and the state is being pushed into the history.
However. We get an url something like this: https://mywebsite.com/index_content
The problem is, when I load this specific URL into my browser I get : "Page not found" ofcourse, because it is trying to search for the index_content folder which does not exist.
Is there a way to check the url by my PHP/jQuery script and to load the correct page into the division? If not, how can I solve this for a generic case.
When I add a new page, I want to spend no- to very less time on the pageswitcher function.
In that way I can also handle non-existing pages.
Thanks in advance!

Reload page when changing hash

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();
});
});

How to redirect from "page.php" to "#page.php" with Javascript or jQuery?

My page runs on php for no js-users. For users with javascript on I load all content dynamic fromt the index in combination with the hashchangevent. So the links all look like www.page.com/#page.php, with a # before it. If the user types it in that way every thing works like charm and the content is being loaded over the index.php
But if a user would enter www.page.com/page.php the page of course ends up on the php page and the dynamic page will of course not work any more except the user will hit the index page and go on navigate from that. So that's not a cool way.
My Question:
How can I redirect user from:
www.page.com/page.php
to
www.page.com/#page.php
when they typed in www.page.com/page.php in the Browser
Of course only with javascript. The Page should work without javascript on normally with php.
Thank you.
When the page loads, change the window.location to the desired URL by deconstructing and reassembling the URI. Unfortunately, you'll have to include this on every page (i.e., page.php) on which you'd like the redirect to happen.
$(document).ready(function () {
// Insert the pathname after the hash, but skip the leading '`'
window.location = "/#" + document.location.pathname.slice(1);
});
It's slightly less clean, but you could also remove the window.location bit from .ready() entirely. This would effect an small performance improvement.
If you want the hash-redirect to affect only the last element of the current path, use the code below, instead.
window.location = "./#" + document.location.pathname.split('/').pop();

how to refresh the browser after the page is loaded

I have a scenario to refresh the browser after the page is loaded for first time or one time.
Because the data is not showing properly when the pages is loaded,and when i refresh the browser it is showing.I don't know the reason.
Many Thanks
So you only want the browser to refresh once? Do something like this.
window.onload = function(){
if(!document.location.hash){
window.location = "#loaded";
}
}
or jquery
$(document).ready(function(){
if(document.location.hash){
window.location = "#loaded";
}
});
But in all honesty this is just a temporary solution. As much as you try to cover it up with quick fixes. I guarantee it will come back to haunt you. Well written and structured code will last a lifetime and can always be reused on future projects.
Invariably, you're going to have to use some JavaScript. What you want is for your refresh code to run when the page is completely loaded. You could use the HTML onload event, but there are problems with this (e.g. it will fire before any images are loaded). I would suggest using JQuery's ready() event, if you want to be sure it fires after the entire page is loaded.
Example:
// NOTE: This will only work with JQuery loaded.
$(document).ready(function(){
location.reload(true);
});
Making this only fire on the first page load is a bit more tricky. You could add an anchor suffix to the URL to keep track of whether you've refreshed the page yet or not, and then only refresh if it is not present in the URL:
$(document).ready(function(){
if(location.hash != "#")
{
// Set the URL to whatever it was plus "#".
// (The page will NOT automatically reload.)
location = "#";
// Reload the page.
location.reload(true);
}
});
Alternatively, you could use the query string, since this will automatically refresh the page when changed:
$(document).ready(function(){
var marker = 'r'; // 'r' is for "refreshed"
if(location.search != "?"+marker)
{
// Set the URL to whatever it was plus "?r".
// (This will automatically force a page reload.)
location = "?"+marker;
}
});
Caveat: With either of these samples, if your user bookmarks the page after the "#" or "?r" tag has been added to the URL, the page won't refresh when they revisit the page. If you want it to be bulletproof, you might have to use a cookie instead.

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 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

Categories