0

So... when I append the <li> below into my <ul>, none of the <div>pseudo-buttons respond when I click them.

$('ul').append('<li class="active">'+ $('#input').val() +'<div class="delete"><span class = "icon">x</span></div><div class = "check"><span class = "icon">---</span></div></li>');

Yet the buttons respond perfectly if I hard code the exact same <li> into my html.

What's the difference?

Here's one of the click functions as an example.

$('.delete').click(function(){
    $(this).parent().fadeOut();
});
dwilbank
  • 2,362
  • 2
  • 21
  • 33

3 Answers3

1

Since the delete elements are created dynamically, you need to use event delegation based event handlers

$('ul').on('click', '.delete', function(){
    $(this).parent().fadeOut();
});

when you use a normal event registration model $('.delete').click(..) it registers the handler to only those elements which already exists in the dom. Newly added elements will not be aware about the handler.

Arun P Johny
  • 365,836
  • 60
  • 503
  • 504
0

Easy. You need attach the event after it has been added to DOM.

$('.delete').click(function(){
 $(this).parent().fadeOut();
});

The above should be called after you append to UL. if append is dynamic then every time after you append

Shoogle
  • 256
  • 1
  • 13
0

Let's suppose there is a selector which can be any string. In our example, let

var selector = '.delete';

If you run a code involving

$(selector)

then it will apply to all the tags matching the selector when the code runs, so your

$(selector).click

missed your tags because they have not existed when you ran the code.

So you should use the .on() instead to register any tags matching the criteria.

Lajos Arpad
  • 45,912
  • 26
  • 82
  • 148