jquery click doesn't work on ajax generated content
JqueryAjaxClickLiveJquery Problem Overview
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>
Jquery Solutions
Solution 1 - Jquery
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.
Solution 2 - Jquery
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() { } );
Solution 3 - Jquery
Instead of:
$(".button").on("click", function() { } );
I used:
$(".container").on("click", ".button", function() { } );
I have used this and it worked.
Solution 4 - Jquery
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.
<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());
});
});
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());
});
});