user1251698
user1251698

Reputation: 2143

jQuery function does not work on appended html

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.net/Y625A/

Upvotes: 2

Views: 1707

Answers (3)

Ligth
Ligth

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

Mark Redman
Mark Redman

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

Adil Shaikh
Adil Shaikh

Reputation: 44740

Use event delegation

$('.container').on('click','.remove',function(){
    alert("remove");
});

Demo --> http://jsfiddle.net/Y625A/2/

Upvotes: 10

Related Questions