jquery click doesn't work on ajax generated content

stergosz picture stergosz · Feb 18, 2012 · Viewed 94.7k times · Source

I am using $(".button").on("click", function(){ });

to click to a button which is on a container but then an ajax call is done and the content gets updated with new stuff and then when i try to click .button it wont work... nothing will get returned when i click the button.

I even tried

$(".button").live("click", function(){ });

or

$(".button").click(function(){ });

How can I make it work?

EDIT : my html:

<div class="container">
   <ul>
       <li>item1</li>
       <li>item2</li>
       <li>item3</li>
   </ul>
   <input type="button" value="reload" class="button" />
</div>

Answer

gdoron is supporting Monica picture gdoron is supporting Monica · Feb 18, 2012

Should be done this way.

$('body').on('click', '.button', function (){
        alert('click!');
    });

If you have a container that doesn't change during the ajax request, this is more performant:

$('.container').on('click', '.button', function (){
        alert('click!');
    });

Always bind the delegate event to the closest static element that will contain the dynamic elements.