Reputation: 7351
I have this code:
window.onload= function() {
window.scrollTo(0, 0.9);
if (navigator.standalone) return;
for (var i= document.links.length; i-->0;) {
document.links[i].onclick= function() {
var req= new XMLHttpRequest();
req.onreadystatechange= function() {
if (this.readyState!==4) return;
document.body.innerHTML= this.responseText;
};
req.open('GET', this.href, true);
req.send();
return false;
};
}
};
It basically gets the href of an a that is clicked and loads that href into the current body. Now the problem is that it only works once. Once the content gets changed, as soon as I click another link (on the new page) it redirects and the url changes. Then the ajax works again since I "really" changed pages and reset the entire thing.
I'm kind of lost here. How can I reset my function to work forever? Thanks,
Christopher
EDIT: Ok so I tried something like this:
function ajax(){
if (navigator.standalone) return;
for (var i= document.links.length; i-->0;) {
document.links[i].onclick= function() {
var req= new XMLHttpRequest();
req.onreadystatechange= function() {
if (this.readyState!==4) return;
document.body.innerHTML= this.responseText;
};
req.open('GET', this.href, true);
req.send();
ajax();
return false;
};}
}
window.onload= function() {
window.scrollTo(0, 0.9);
ajax();
};
But to no avail... calling the ajax() function when it finishes is not enough apparently. Can anyone help me a bit more :s. This isn't my field of expertise :).
Upvotes: 3
Views: 353
Reputation: 987
When you set document.body.innerHTML you are replacing the entire document, which means the onclick events you wired up are gone. You have to rebind the click events to your new links.
Upvotes: 1
Reputation: 13200
You're removing the links when you replace the body with your data.
This is also the kind of code that suggests using a library like jQuery. In that case, almost all your code is reduced to this, and takes care of cross-browser issues as well:
$('a').live('click', function() {
$.get( this.ref , function(data) {
$('body').html(data);
});
return false;
});
Upvotes: -2
Reputation: 14729
You are replacing the whole document, including the links you bound the AJAX handler to.
window.onload will only fire when the document is loaded, not when the ajax call completes.
Put your onload handler in a new function then call it in manually your ready state change handler.
Upvotes: 1
Reputation: 413720
You'll have to re-establish the "click" handler after blasting the original <body>
contents with the response. Since everything in the old DOM is gone after the response comes back, the handler binding is gone too.
Upvotes: 2