0

I've got a function that adds or removes a class when clicked:

$('button').on('click', function(){
// do stuff
});

However, I am also loading stuff with AJAX. When I load the AJAX, the click event does not work with the newly loaded content.

Is there a way I can get the function to work globally, rather than have to repeat it within the callback? Would it be something like change or live?

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247

1 Answers1

0
$(document).on('click', 'button', function(){
    // do stuff
});

This works with newly added elements. You can change document to whatever parent element you have.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • Thanks. What is jQuery doing differently to make this happen? –  Jun 14 '14 at 18:46
  • @tmyie - I'm not sure how exactly they achieve this effect but you can check their [source code](http://code.jquery.com/jquery-2.1.1.js) for that. (line 4785) – Derek 朕會功夫 Jun 14 '14 at 22:02