I'm just messing around with ajax for the first time.
At the moment I'm loading text from text files according to the url.
Here's how I'm doing it:
var home_url = "blahblah/index.html#home";
var test_url = "blahblah/index.html#test";
$(document).on("click",".ajax_load",function(){
if (location.href === home_url) {
$("#main").load("src/home.txt");
};
if (location.href === test_url) {
$("#main").load("src/test.txt");
};
});
This works, however the content isn't loading until after I have pressed the button for the second time. Easier to understand:
button press -> 2nd button press -> content loaded
I think this happens because my code doesn't register the url until after the first press, and then the if
statements check whether content needs to load, but this is only triggered until the button is clicked again.
Can anyone help me make the content load with only one button press?
Thanks.
The problem is, that the links change the "location.href" after the event is fired. So the first time you click, the wrong (or none) ajax-load code will be executed and afterwards the URL is changed, so the second click checks the correct URL.
So the solution I suggest is this: don't check the location url but the url you specified at the links:
$('.ajax_load').bind('click', this, function(){
if (this.href === home_url) {
$("#main").load("src/home.txt");
};
if (this.href === test_url) {
$("#main").load("src/test.txt");
};
});
Beware: "this.href" always contains the complete URL, even if the links are specified with a simple anchor:
<a href="#home">home</a>