80

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>
Cœur
  • 37,241
  • 25
  • 195
  • 267
stergosz
  • 5,754
  • 13
  • 62
  • 133
  • 1
    Please show What is being returned by the ajax call. – ron tornambe Feb 18 '12 at 21:39
  • And the rest of jQuery that attaches the listener. What you're describing is exactly what `live` is supposed to handle, so it's strange that that isn't working. – Brandan Feb 18 '12 at 21:41
  • i have a ul where i click on them and simply echo "test" in javascript with .on("click") but when i click the button it will do an ajax call and reload the ul but then it will stop doing nothing when i click the button.. it wont return anything. – stergosz Feb 18 '12 at 21:48

4 Answers4

161

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.

Kzqai
  • 22,588
  • 25
  • 105
  • 137
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • Thanks for the answers! Still think this is very weird and doesn't feel allright to use this way. Wish jquery had a better way of handling these kind of situations – Miguel Stevens Mar 06 '14 at 13:12
  • 1
    @MiguelStevens, read [on's docs](http://api.jquery.com/on) once you read and understood the concept, it won't be weird and will make perfectly sense. – gdoron Mar 06 '14 at 14:05
  • But how would I write parent for this... $("input#someId").autocomplete({//some code});...there is no on event here.. – Dragon Oct 27 '15 at 13:59
  • 1
    @Sadaquat, I suggest writing a full question with all the required details in a different thread. If you won't get an answer, you can ping me with a comment and I'll try my best to help. – gdoron Oct 27 '15 at 14:14
  • i did the same but its not working..any suggestions? – Zaki Mustafa Apr 06 '17 at 14:34
  • 1
    Finally I found the solution I was looking for! Thank you sir – K. P. Apr 18 '19 at 14:28
41

Ok i solved my problem by using the .on() function correctly since i was missing one parameter.

instead of

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

i used

$(".container").on("click", ".button", function() { } );
stergosz
  • 5,754
  • 13
  • 62
  • 133
8

Instead of:

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

I used:

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

I have used this and it worked.

Flexo
  • 87,323
  • 22
  • 191
  • 272
Macc
  • 81
  • 1
  • 1
3

Is this what you're trying to do? Note, I'm putting the $.on() on the parent, but selecting the .button for the action.

.on( events [, selector] [, data], handler(eventObject) )

selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.

http://api.jquery.com/on/

<div id="stuff">
    <button class="button">Click me!</button>
    <p>Stuff</p>
</div>

var $stuff = $('#stuff'),
    ajaxContent = $stuff.html();

$stuff.on('click', '.button', function(){
    $.get('/echo/html/', function(){
        $stuff.empty();
        console.log($stuff.html());
        alert($stuff.html()); // Look behind, #stuff is empty.
        $stuff.html(ajaxContent);
        console.log($stuff.html());
    });
});

http://jsfiddle.net/62uSU/1

Another demonstration:

var $stuff = $('#stuff'),
    ajaxContent = $stuff.html(),
    $ajaxContent,
    colors = ['blue','green','red'],
    color = 0;

$stuff.on('click', '.button', function(){
    $.get('/echo/html/', function(){
        color++;
        if (color == colors.length) color = 0;
        console.log($stuff.html());
        alert($stuff.html());
        $ajaxContent = $(ajaxContent);
        $stuff.append($ajaxContent).css('color', colors[color]);
        console.log($stuff.html());
    });
});

http://jsfiddle.net/62uSU/2/

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104