WJ___ WJ___ - 1 year ago 45
Javascript Question

How do I detect if elements being loaded by load() have finished loading?

I am trying to load some elements from another page under my site, and I did.
But I also tried to apply some jquery action to the elements being loaded.
But, the scripts that I wrote for them are being skipped because they run before the elements are loaded.
Any idea how to detect if the element loading is complete?
(Maybe it is a stupid question, but I really cant find an answer).

This is how I load my elements:

$('#homeCat2').load('category.php?id_category=2 #product_list');

I tried something like this, but it was no use:

$('#homeCat2').load('category.php?id_category=2 #product_list',whenCompleteLoad());

function whenCompleteLoad(){
var itemNum = $('.ajax_block_product').length;

I also tried to put the code for those elements in to the $(document).ready();
but, no luck....

Any suggestions?

Answer Source

You are passing the output of whenCompleteLoad() to the callback slot of your .load() function. This happens because when you add the parentheses, you call the function.

Removing the parentheses references the actual function, which is what you want:

$('#homeCat2').load('category.php?id_category=2 #product_list',whenCompleteLoad);

Or you can use an anonymous function (I prefer this method):

$('#homeCat2').load('category.php?id_category=2 #product_list', function() {
  var itemNum = $('.ajax_block_product').length;