Interactive "to do" list


#1



The first part of adding elements, works just fine, but it will not remove the added li elements after clicking on them...

Please advice...


$(document).ready(function() {
    $('#button').click(function() {
        $('.list').append('<li>'+$('input:text').val());
    });
    
    $('li').click(function() {
        $(this).remove();
    });
});


#2

The click event that you have written is not being bound to anything since there are no LI elements when we first run the code. Those lines of code will never run again.

This is where on() comes in. The parent object, .list does exist at run time so we can bind to it, then delegate to the event object, once there is one.

$('.list').on('click', 'li', function() {
    $(this).remove();
});

Now the listener is dynamic in nature and will respond to any clicks that take place within it, even on newly created LI's.


#3

Thank you indeed it is working now. Though that is strange, the jQuery course did not cover this on() command yet, so they probably were expecting some other way of doing that task...


#4

The only other way to do it is to bind the listener to each newly created LI. But the problem with that is that when the LI is removed, the listener is still there, taking up memory. We need to unbind the listener before we remove the element. This can get messy.


#5

That was one of these multiple-step tasks. I just did everything in the first step, and then after moved on, the .on() has been introduced. The first step supposed to be just the $(document).ready(); part. Need to put more attention to instructions.

Anyway, thank you for your input.