1

I'm trying to create a dynamic item list that can be added to and removed from with animations. The problem I have is new items can't be removed. any ideas on what I'm doing wrong?

http://jsfiddle.net/waspinator/nZ9y2/1/

html

<button class="add-item-button"> add item </button>
<div id="list">
    <!-- prepend new item here -->
    <div class="item">
        First Item
        <span class="remove-item">x</span>
    </div>
    <div class="item">
        Second Item
        <span class="remove-item">x</span>
    </div>  
</div>

css:

#list{
    width: 140px;
}

.remove-item{
    font-family: sans-serif;
    float: right;
    margin-top: -6px;
    cursor: pointer;
}

.item{
    color: white;
    background: CornflowerBlue;
    margin-bottom: 4px;
    padding: 4px;
    border-radius: 4px;
}

.add-item-button{
    margin-bottom: 10px;
    width: 140px;
}

js

var item_number = 1;

$('.remove-item').click(function(){  
    $(this).parent().animate({opacity: 0}, function () {
        $(this).slideUp();
    });
});


$('.add-item-button').click(function() {
    var new_item = '<div class="item">' +
        'New Item ' + item_number +
        '<span class="remove-item">x</span>' +
        '</div>'

    $(new_item).prependTo('#list').hide().slideDown();
    item_number = item_number + 1;
});
waspinator
  • 6,464
  • 11
  • 52
  • 78

2 Answers2

1

Bind to the #list as it is always in the dom, then select on the .remove-item class. Here is the fiddle: http://jsfiddle.net/nZ9y2/3/

var item_number = 1;

var remove = function() {  
    $(this).parent().animate({opacity: 0}, function () {
        $(this).slideUp();
    });
}

$('#list').on('click', '.remove-item', remove);

$('.add-item-button').click(function() {
    var new_item = '<div class="item">' +
        'New Item ' + item_number +
        '<span class="remove-item">x</span>' +
        '</div>' 
    $(new_item).prependTo('#list').hide().slideDown();
    item_number = item_number + 1;
});
Victory
  • 5,811
  • 2
  • 26
  • 45
0

change the js function for removing to

$('#list').on('click', '.remove-item', function(){  
    $(this).parent().animate({opacity: 0}, function () {
        $(this).slideUp();
    });
});

http://jsfiddle.net/waspinator/nZ9y2/4/

waspinator
  • 6,464
  • 11
  • 52
  • 78