Reputation: 2143
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:
Upvotes: 2
Views: 1707
Reputation: 330
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.com/ofoteq/1/edit
Upvotes: 1
Reputation: 24515
Try using live
to bind the events, this will bind them when the new items are created:
$('.add').live('click', function(e){
});
Upvotes: 1
Reputation: 44740
Use event delegation
$('.container').on('click','.remove',function(){
alert("remove");
});
Demo -->
http://jsfiddle.net/Y625A/2/
Upvotes: 10