Javascript: history not loading page - javascript

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

Related

Ajax .load refresh/back button

I'm opening part of my pages in div with Ajax. But when i refresh or hit the back button it just doesnt do what it should.
I read and tried a lot to get this to work but it just dont want to work.
I'm at a point that when i hit the the refresh or back button my address bar give the right page, but my div doenst change (e.g. address bar says: /projects.php but the page/div is still on index.php)
I just want to use the back/forward buttons and when i refresh the page it has to stay at the same page and dont go back to the first mainpage.
Here is my code, hope someone have a solution:
Html - my menu
<div id="buttons">
<a class="menu" id="page1" href="#Home">Home</a><span>|</span>
<a class="menu" id="page2" href="#Projects">Projects</a><span>|</span>
<a class="menu" id="page3" href="#About">About</a><span>|</span>
<a class="menu" href="#Contact">Contact</a>
</div>
.load part
$(document).ready(function() {
$("#page1").click(function(){
$('#content').load('index.php #content');
});
$("#page2").click(function(){
$('#content').load('projecten.php #content');
});
$("#page3").click(function(){
$('#content').load('overons.php #content');
});
});
.haschange part
$(function(){
// These two properties, set after jQuery and the hashchange event plugin are
// loaded, only need to be used when document.domain is set (to fix the "access
// denied" error in IE6/7).
$.fn.hashchange.src = '../../document-domain.html'; //--- I still dont know what to do with this, but i guess its only for IE6/7 ---//
$.fn.hashchange.domain = document.domain;
// Bind an event to window.onhashchange that, when the hash changes, gets the
// hash and adds the class "selected" to any matching nav link.
$(window).hashchange( function(){
var hash = location.hash;
// Set the page title based on the hash.
document.title = 'The hash is ' + ( hash.replace( /^#/, '' ) || 'blank' ) + '.';
// Iterate over all nav links, setting the "selected" class as-appropriate.
$('#buttons a').each(function(){
var that = $(this);
that[ that.attr( 'href' ) === hash ? 'addClass' : 'removeClass' ]( 'selected' );
});
})
// Since the event is only triggered when the hash changes, we need to trigger
// the event now, to handle the hash the page may have loaded with.
$(window).hashchange();
});
When you only change the fragment the page doesn't reload or anything.
This is the thing with SPA (Single Page Applications) - they don't reload the page. Which is why e.g. Gmail maintains the page state even though the URL after the # (aka fragment) changes. Open a different folder and/or email and see that the URL fragment changes.
You'll need to listen to those events and do actions similar to your $('#pageN').click() handlers yourself. Also do something similar if a user opens http://yourserver/#page2 directly. And think about SEO if that is applicable to you.
See a similar question: javascript - Detecting Back Button/Hash Change in URL - Stack Overflow (do try to use the HTML5 API if you can),
See e.g. Intelligent State Handling ยท browserstate/history.js Wiki for some background info.
Or create completely separate pages where the URL path (before the # changes). Like in the good old days.

Is it possible to make a link to a one page webpage to open and position itself at a specific article?

Is there a way to open a specific artical via an external link and focus on it when the links open on a one page wepage?
I have a webpage that shows content as you click on links by hiding and showing the divs. What i want is to make an external link to my webpage in the form of mywebpage/(div's name) and have the link open my page but showing the content of that div right away, instead of its usual opening content you would get when clicking on just the ordinary mywebpage link.
Is it possible? And how?
Short answer: yes.
Long answer: You will have to examine the URL's hash on page load and manually translate that into hidden or shown divs (or other positioning).
While you're at it, you could include browser history support when your divs are opened and closed.
Pulling apart what I did for http://www.tipmedia.com (Segment starts on line 322 of the page source)
//on page ready
$(document).ready(function() {
//examine hash
if(window.location.hash == "#thanks") {
//scroll to an anchor tag, slight delay to insure correct page height
setTimeout(function() {
$('html,body').animate({scrollTop:$("#contact").offset().top}, 0);
},500);
//hide and show necessary divs
$("#contactThanks").css({"display":"block"});
$("#contactIndex").css({"display":"none"});
$("#contactGeneral").css({"display":"none"});
$("#contactMeeting").css({"display":"none"});
$("#contactCareers").css({"display":"none"});
//clear the hash (not necessary for your use)
window.location.hash = "";
}
}
The history stuff is easy too, I used Modernizer.js for the best cross browser support, but it looks like this (non-Modernizer use is very similar)
//during the hide/show of new content...
//if history is available
if(Modernizr.history) {
//this data is whatever it is you wish to save
lastPageState = { div:divName, pos:amount, page:lastLoadedPage };
history.pushState(lastPageState, divName.substring(1,divName.length-6), "index.html");
}
//...
//then later, the popsate event handler
window.onpopstate = function(event) {
//examine event.state and do whatever you need to
//example segment starts line 989
//Whatever data you saved would be read here and you would do the appropriate action,
//hiding or showing divs, reloading AJAX content, etc.
}
Yes, you can use an anchor link.
So in your target page name the div with an id,say div id="target".
Then in the referring page use a link in this form
Referring Page:
GO to Target Info...
Target Page:
<div id="target">
...content...
</div>
FYI-"target" is just an example name, it could be anything...

How do I relocate the user to contents of another page without page refresh when navigating?

Im using javascript - ajax and jquery to load all contents from php files which is under (#menu a)[see below 'you.php'] without refreshing the page when navigating across the page - which works perfectly.
However, how do I create a hyperlink of somesort on content-A (which loads and shows all the contents from home.php) when clicked, it relocates & shows the user to/the contents of settings.php(B).
Please note my href hyperlinks doesn't have .php at the end. The 'general.js' file explains why.
(you.php):
<div id="menu">
Home
Settings // Content (A)
</div>
<div id="content"><div>
<script src="./js/jquery-2.1.4.min.js"></script>
<script src="./js/general.js"></script>
(general.js):
$(document).ready(function() {
// initial content that will be loaded first upon logging in:
$('#content').load('home.php');
// handle menu clicks
$('#menu a').click(function(){
var page = $(this).attr('href');
$('#content').load('' + page + '.php');
return false;
});
});
(home.php):
<h1> welcome to homepage </h1>
Would you like to go to your settings?
Click here: <a href="settings.php>Settings</a>
Obviously the problem with doing the href hyperlink like this in home.php, is that it goes directly to the settings.php page. Which makes my general.js (ajax) and jquery file pointless.
Since the whole point of using ajax and jquery is for smooth navigation and no page refresh upon navigating around the website.
and No, I do not want to load the contents of settings.php within the contents of home.php, 'loadception' is not what I'm looking for.
This is my simple question, I would like a simple answer in php,javascript,ajax.
Any ideas?
You need to use event delegation. To better performance in my example, all links that must be loaded into "#content" have a class "open" so, in jquery you could do some like this:
$('#content').on('click', '.open', function(e) {
e.preventDefault();
var page = $(this).attr('href');
$('#content').load('' + page + '.php'); // concat .php if it's only necessary
});
Updated
I created a demo on github: https://github.com/josemato/stackoverflow/tree/master/spa-event-delegation

Popstate with Hashtags?

I have a site that uses AJAX to dynamically load content into a div.
The links to do so are anchors with href="#" and an onclick event to trigger the AJAX.
This leaves me without a history when I click back, so if I load one page, then another and click back, it does nothing.
A basic version of the code is this:
<script type="text/javascript">
function loadXMLDoc(url)
{
<!-- Load XML Script here. -->
}
</script>
</head>
<body>
<div id="myDiv">
<!-- Target div. -->
</div>
Click Me.
Click Me.
Click Me.
</body>
What I would like to know is, can I give each link a different "#" and then use a popstate handler to call the appropriate event, so if I click link 1, 2 and then 3 and then start hitting the back button, it'll go back to 2 and then 1 etc..
I was going to use history.js and start using pushstate in the loadXML script but I think the whole manipulating history thing is a bit dirty and unreliable.
Am I thinking on the right lines or is there a better way?
Currently all my links just use "#" so that it pops back to the top of the page when loading more content but I'd like to be able to go back if possible.
Any help would be great.
Browser saves hashtags to history properly. Just add hashtag #1 to this question page, hit enter, change it to #2, hit enter, change it to #3, hit enter. Now click back button, and you'll see hash changes from #3 to #2. I recommend to change only hash itself on link click and react on page hash change and page load events.
function react() {
var hash = window.location.hash.replace("#", "");
loadXMLDoc(hash + ".txt");
};
document.body.onload = function() {
react();
window.onhashchange = react;
};
Click me
Click me
Click me
Please note that onhashchange event does not supported by old IE. The only way to deal with it if you want is to define timer with setInterval and check hashes equality.
Try to use combination of LocalStorage and HistoryAPI.
When you load XMLDoc store it in LocatStorage, when back is pressed - load data from storage, not from web.
A bit code above.
/* Handling history.back added */
window.onpopstate = function(event) {
yourHandleBackFunction(event.state);
};
function yourHandleBackFunction(renderTs) {
/*Check TS and load from localStorage if needed*/
};

Javascript : Change the function of the browser's back button

Is there a way to make the user's back button on their browser, call a javascript function instead of going back a page?
You can't override the behaviour that if a user follows a link to your page, clicking Back will take them off it again.
But you can make JavaScript actions on your page add entries into the history as though they were clicks to new pages, and control what happens with Back and Forward in the context of those clicks.
There are JavaScript libraries to help with this, with Really Simple History being a popular example.
yes, you can. Use this js:
(function(window, location) {
history.replaceState(null, document.title, location.pathname+"#!/stealingyourhistory");
history.pushState(null, document.title, location.pathname);
window.addEventListener("popstate", function() {
if(location.hash === "#!/stealingyourhistory") {
history.replaceState(null, document.title, location.pathname);
setTimeout(function(){
location.replace("http://www.programadoresweb.net/");
},0);
}
}, false);
}(window, location));
That will redirect your back button to the location.replace you specify
I think this will do the trick.
you can write your custom code to execute on browser back button click inside onpopstate function.
This works in HTML5.
window.onpopstate = function() {
alert("clicked back button");
}; history.pushState({}, '');
I assume you wish to create a one-page application that doesn't reload the website as the user navigates, and hence you want to negate the back button's native functionality and replace it with your own. This can also be useful in mobile web-apps where using the back button inside apps is common to close an in-app window for example. To achieve this without a library, you need to:
1st. Throughout your application modify the window's location.hash instead of the location.href (which is what tags will do by default). For example, your buttons could fire on click events that modify the location.hash like this:
button.addEventListener('click', function (event) {
// Prevent default behavior on <a> tags
event.preventDefault()
// Update how the application looks like
someFunction()
// Update the page's address without causing a reload
window.location.hash = '#page2'
})
Do this with every button or tag you have that would otherwise redirect to a different page and cause a reload.
2nd. Load this code so that you can run a function every time the page history changes (both back and forward). Instead of the switch that I used in this example, you can use an if and check for other states, even states and variables not related to location.hash. You can also replace any conditional altogether and just run a function every time the history changes.
window.onpopstate = function() {
switch(location.hash) {
case '#home':
backFromHome()
break
case '#login':
backFromLogin()
break
default:
defaultBackAnimation()
}
}
This will work until the user reaches the first page they opened from your website, then it will go back to new tab, or whatever website they were in before. This can't be prevented and the teams that develop browsers are patching hacks that allow this, if a user wants to exit your website by going back, they expect the browser to do that.
If you are creating a one-page web application, where your html body has different sections and you want to nevigate through back button to the previous section you were. This answer will help you.
Where your website sections are differentiated by #. Such as:
your-web-address.com/#section-name
Just follow a few steps:
Add a class and a id in every section in you html body. Here it is ".section"
<section class="section" id="section-name">...</section>
Add two CSS class in your linked css (e.g., style.css) file to your html (e.g., index.html) file such:
.section .hide {
display: none;
}
.section .active{
dislplay: block;
}
Add this JavaScript function in you linked .js (e.g., main.js) file to your html file.
window.onpopstate = function () {
if (location.hash !== "") {
const hash = location.hash;
// Deactivating existing active 'section'
document.querySelector(".section.active").classList.add("hide");
document.querySelector(".section.active").classList.remove("active");
// Activating new 'section'
document.querySelector(hash).classList.add("active");
document.querySelector(hash).classList.remove("hide");
}
}

Categories