Harry Thomas
Harry Thomas

Reputation: 25

onclick events in jquery on AJAX loaded content

I am having trouble using the ".on" method in jQuery on content that has been inserted via AJAX. I currently use ".live", however this is deprecated and ".on" is what I'm after.

My working code is:

$('.folderadmin').live("click", function() 
{   
   // Do stuff
})  

When I replace the .live with .on, it fails to work. I believe it is because the element .folderadmin is loaded via AJAX - thus why we needed to use .live to access it. How can I access the DOM and recognize .folderadmin with .on?

Upvotes: 0

Views: 4551

Answers (2)

Evan Levesque
Evan Levesque

Reputation: 3213

you should check your jQuery version since .on was added on jQuery version 1.7 where the .live() method is apparently deprecated
.on()
it should be like :

$(".folderadmin").on("click", function(){
  //enter code here
});

Upvotes: 0

xdazz
xdazz

Reputation: 160893

$('.folderadmin').live("click", function() {   
   // Do stuff
});

is same as

$(document).on("click", '.folderadmin', function() {
  // Do stuff
});

But it is not necessary to bind to document, you could bind to the parents container of .folderadmin which has already exists in the dom tree.

$('#the_parent_id').on("click", '.folderadmin', function() {
  // Do stuff
});

Upvotes: 5

Related Questions