0

When adding a list item to my ul, the jQuery on events don't seem to fire or work on these. From my understanding, using on instead of say .click() should work for all items, whether created in HTML or added later via javascript/etc.

<div class="container">
    <div class="list">TO-DO LIST<div class="glyphicon glyphicon-plus"></div></div>
    <ul class="toDoList" style="list-style: none;">
        <li id="addToDo"><input type='text' id="addToDoText" placeholder="Add New ToDo"></input></li>
        <li><span><i class="fa fa-trash"></i></span>Buy Robes</li>
        <li><span><i class="fa fa-trash"></i></span>Fight Malfoy</li>
        <li><span><i class="fa fa-trash"></i></span>Buy New Wand</li>
        <li><span><i class="fa fa-trash"></i></span>Kill Voldemort</li>
        <li><span><i class="fa fa-trash"></i></span>Feed Hedwig</li>
        <li><span><i class="fa fa-trash"></i></span>Send Owl to Sirius</li>
        <li><span><i class="fa fa-trash"></i></span>Do Dishes</li>
        <li><span><i class="fa fa-trash"></i></span>Wash Robes</li>
        <li><span><i class="fa fa-trash"></i></span>Buy Hagrid's Birthday Gift</li>
    </ul>
</div>

and my jQuery:

$('ul.toDoList li').on("click", function(){
    $(this).toggleClass('completedItem');
});

$("input").on("keypress", function(e){
    if(e.which == 13){
        new_text = $(this).val();
        $(this).val("");
        add_toDo(new_text);
    }
});

$('li .fa-trash').on("click", function(){
    $(this).closest('li').remove();
});

function add_toDo(item){
    console.log("adding: "+item);
    $('ul.toDoList').append('<li><span><i class="fa fa-trash"></i></span>'+item+'</li>');
};

When I add an item, and click tne item, it doesn't toggle the completedItem class, nor can I remove it by clicking the fa-trash icon.

BruceWayne
  • 22,923
  • 15
  • 65
  • 110

1 Answers1

1

research more about .on() and .click() jquery functions. Using on() its not mean bind event to all specific elements, the selector before that will choose what elements to be affected by this function. any ways you adding new element into the DOM, so jquery cached old elements before we adding new element and totally unaware of new ones. this code most be edited in this ways:

$(document).on("click", "ul.toDoList li", function(){
    $(this).toggleClass('completedItem');
});

$(document).on("click", "li .fa-trash", function(){
   $(this).closest('li').remove();
});
Colin Cline
  • 1,291
  • 1
  • 12
  • 25
  • I added the `$(document).find()` but that didn't seem to do anything. Edit: I was able to get it with `$(document).on('click', 'li .fa-trash', function(){...});`. – BruceWayne Dec 03 '17 at 21:37