1

I am adding some list items to a list on the go using jquery. There are two classes given to each list items. One controls CSS attributes and other controls the click on the list item. The list item looks something like this :

< li class="il l3" >Gigabyte Wars< /li >

Here 'il' controls CSS and l3 controls the click function.

My problem is that when I add list items on the go, the regular click function defined for all list items does not work for the new ones. Any suggesstions ?

Gagan93
  • 1,657
  • 2
  • 19
  • 36

2 Answers2

6

Instead of using:

$('.l3').click(function(){});

Use (be more specific than document if you can:

$(document).on('click', '.l3', function(){});

The latter will create a delegated event handler which will handle events for any elements created in the future as well as the elements that already exist.

Justin Niessner
  • 229,755
  • 35
  • 391
  • 521
1

The selector $(".l3") adds the event handler to existing elements in the DOM matching it. If you're adding new items, you can either specify the event handler on the document, as noted in Justin's answer, or, if you need finer-grained control, you can dynamically add the event handler to new items:

$("<li>", { class: "l3" }).appendTo(someList).click(function () { ... });
Community
  • 1
  • 1
Gingi
  • 1,940
  • 1
  • 17
  • 31
  • I use this $('.orderedList').append('
  • ' + $('.nam').val() + '
  • ').click(function() { alert("Description : \n "+$('.desc').val().trim()+"\n\nLocation : \n"+$('.loc').val().trim()); }); and it doesn't work ! – Gagan93 Jun 30 '14 at 15:45
  • 1
    You're assigning the click handler to the list (`$('.orderedList')`), not the underlying list items. Also, you're adding raw HTML that jQuery parses and appends. You might want to use the `appendTo` technique: `$("
  • ", { class: "il l"+i }).text($('.nam').val()).appendTo($('.orderedList')).click(function () { ... })`
  • – Gingi Jun 30 '14 at 16:38