0

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.

1
  • Time for you to show some HTML and check your code is in the correct context in the snippet. Besides improving location.href to location.hash, I can't see why the ajax couldn't trigger (considering you are doing the rest relatively good) Commented Sep 19, 2012 at 20:21

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.