1

I should create some kind of a checklist.

If the user clicks on some task (in this case a <li>) the task should disappear and get strike-through. I solved this with toggling jQuery class:

$('li').click(function() {
   $(this).toggleClass("checked unchecked");
});

Everything works fine. If the user clicks on a list item, the class changes from "unchecked" to "checked".

But there is an option to add new tasks (the little plus icon above). If you add an new list item, the class changer does not work for this. If you click on it, nothing happens.

I hope you guys understand me, my english is not so great :-)

Have a look: http://www.predatordesign.de/todoliste.

VisioN
  • 132,029
  • 27
  • 254
  • 262

3 Answers3

1

You need to use event delegation for attaching events to dynamically added element.

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

 $('.todo-list').on('click','li',function() {
    $(this).toggleClass("checked unchecked");
 });
Milind Anantwar
  • 77,788
  • 22
  • 86
  • 114
1

This is because new dynamically created items don't exist when you bind click handler to <li> elements. To solve the issue you may use event delegation with on method:

$('.todo-list').on('click', 'li', function() {
    $(this).toggleClass('checked unchecked');
});

Here .todo-list is a static parent element of <li> elements.

MORE: https://learn.jquery.com/events/event-delegation/

VisioN
  • 132,029
  • 27
  • 254
  • 262
0

You have to bind the event to the dynamically generated events

$('ul').on("click", "li", function() {
   $(this).toggleClass("checked unchecked");
});
Tushar
  • 11,306
  • 1
  • 21
  • 41