amoeba
amoeba

Reputation: 105

jquery .on() not working after .load() of php file

I'm attempting to run the following simple bit of code on an html snippet contained in a php file, loaded with jquery's .load() function:

$(".thumbnail").on("click", function(event){

    alert("thumbnail clicked");
});

However, I can't seem to get it to work on this portion of my page. I have other calls to elements not loaded via ajax and they work fine with the .on() function. I was under the impression that .on() would recognize ajax loaded content.

My .thumbnail elements are pictures in img tags contained within a series of divs all loaded via ajax, jquery can't seem to find any of this content. All of my code is contained within the ready function.

Is there a way to get jquery to recognize these new elements?

Thanks.

Upvotes: 1

Views: 1790

Answers (1)

adeneo
adeneo

Reputation: 318252

You need a delegated event handler for dynamic content :

$('#container').load('somefile.php');

$('#container').on('click', '.thumbnail', function(event){
     // do stuff
});

The closest non-dynamic parent would probably be the element you're loading the content into, and you need to attach the event handler to that element, filtering based on the .thumbnail class, like the code above.

Upvotes: 5

Related Questions