I want to append a div with jQuery and then use jQuery click function on a class which is inside the appended div. Here's my code, it does not work if I append the div, however it works fine if the div already exists in the html.
HTML:
<div class="add">
Add item
</div>
<div class="container">
</div>
jQuery:
$('.add').click(function(e){
e.preventDefault();
var box = '<div class="box"><div class="remove">x</div></div>'
$('.container').append(box)
});
$('.remove').click(function(){
alert("remove");
});
Demo:
/
I want to append a div with jQuery and then use jQuery click function on a class which is inside the appended div. Here's my code, it does not work if I append the div, however it works fine if the div already exists in the html.
HTML:
<div class="add">
Add item
</div>
<div class="container">
</div>
jQuery:
$('.add').click(function(e){
e.preventDefault();
var box = '<div class="box"><div class="remove">x</div></div>'
$('.container').append(box)
});
$('.remove').click(function(){
alert("remove");
});
Demo:
http://jsfiddle/Y625A/
Share Improve this question asked May 22, 2013 at 12:33 user1251698user1251698 2,14313 gold badges35 silver badges52 bronze badges3 Answers
Reset to default 10Use event delegation
$('.container').on('click','.remove',function(){
alert("remove");
});
Demo -->
http://jsfiddle/Y625A/2/
- http://api.jquery./on/
- http://learn.jquery./events/event-delegation/
Try using live
to bind the events, this will bind them when the new items are created:
$('.add').live('click', function(e){
});
You have to bind the click even once you create the element:
$('.add').click(function(e){
e.preventDefault();
var box = "<div class='box'><div class='remove'>x</div></div>"
$('.container').append(box)
$('.remove').click(function(){
alert("remove");
});
});
http://jsbin./ofoteq/1/edit