2

I have this script and I would like to make it work with dinamically added elements from database:

$( ".select-song li" ).each(
function( intIndex ){
    $( this ).bind (
        "click",
        function(){
          if($(this).hasClass('checked')){
           $(this).removeClass('checked');
          }
          else{
            $(this).addClass('checked');
          }
        }
        );
}
);

Elements are added in like this:

$('.select-song').append('<li>sth here</li>');

I know that I should to use on function but I have no idea how to implement it here.

El Danielo
  • 710
  • 8
  • 17

2 Answers2

2

Delegating event using on():

$(".select-song").on("click", "li", function(){
    $(this).toggleClass('checked');
});
A. Wolff
  • 72,298
  • 9
  • 84
  • 139
0

Delegate the event from .select-song to li:

$(".select-song").on("click", "li", function () {
    if ($(this).hasClass('checked')) {
        $(this).removeClass('checked');
    } else {
        $(this).addClass('checked');
    }
});

This way every time you append a newly created li in .select-song, the event will be bound to it. Remember that it's always best to delegate from the nearest non-dynamic parent. If you delegate from body or document for example, the performance will not be the same as the event will have to propagate until the matched selector.

taxicala
  • 20,376
  • 7
  • 31
  • 65
  • `If you delegate from body or document for example, the performance will not be the same` Is that really matter for a click event? I mean even Chuck Norris cannot be fast enough to click fster than browser can handle it. ;) – A. Wolff Oct 01 '15 at 16:08
  • yes, it does matter in large applications where many events are interacting together. – taxicala Oct 01 '15 at 16:09
  • and it also matters if the element that should receive the event is way down in the DOM tree. – taxicala Oct 01 '15 at 16:10
  • This is more important for cleaning events when static container is removed e.g, imho – A. Wolff Oct 01 '15 at 16:11