Question

I am trying to manipulate some elements after I load them using .load(). I have everything loading correctly, but I can't seem to target any elements within any of the loaded elements. This seems like something that would be easy, but I just can put my finger on it.

I am using a callback after the elements load, but the DOM seems to not be aware of their existence?

function load_page(){
    $('#page_name').load("/page-name/ .page", null, load_complete());
}

function load_complete() {
    $('#page_name .book_img').addClass('hello');
}

Ok, this is where I am at now. I have added...

$('#wrapper').ajaxComplete(function() {
    $('#page_name .book_img').addClass('hello');
}

which works. There must be a difference between the .autoComplete and the callback which is packaged with the .load() function. I don't really like this because it is called every time an AJAX event is finished loading, but it does get me a little further down the road.

Anybody have anything better?

[EDIT]

I also tried...

$('#wrapper').ajaxComplete(function() {
    $('#page_name .book_img').addClass('hello');
}

Which is kind of nice since it waits till all AJAX calls are done before calling the function. Maybe this is the way to do it, but it still seems like the .load() function would take care of this?

No correct solution

OTHER TIPS

Looks like your executing your callback function instead of passing it to the load method:

function load_page(){
    // $('#page_name').load("/page-name/ .page", null, load_complete());
    $('#page_name').load("/page-name/ .page", null, load_complete);
}

function load_complete() {
    $('#page_name .book_img').addClass('hello');
}

So what was being passed to the load method is null because there is no return value in load_complete

Sometimes the HTML takes a bit of time to render. Try adding a delay before accessing the new content:

$('#page_name').load("/page-name/ .page", null, window.setTimeout(function(){load_complete()},50);

You have to include the javascript that is to manipulate your loaded objects in the item that's getting loaded. This is because it has already ran through all your javascript.

edit

Try this, set the asynchronicity to false so it you can add a callback after its loaded.

$.ajax ({
  async: false,
  type: "GET",
  dataType: "html",
  url: "/page-name/ .page",
  complete: function(){load_complete()};
});

update

Hey, there's also this shorthand get statement I use occasionally. It surprises me that these are not working in your script..

$.get($(this).attr('href'), function(response) { $('#content').html(response); });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top