tags:

views:

219

answers:

6

I'm having a problem triggering events on items that have been added to the page. In the following example, if you click X it will remove one of the items, but you if you add an item you can't remove it.

Here's the list:

<ul id="mylist">
    <li>Item 1 <a class="remove">X</a></li>
    <li>Item 2 <a class="remove">X</a></li>
</ul>
<a class="add">Add</a>

Here's the jQuery:

$('.add').click(function(){ 
 $('#mylist').append('<li>Item 3 <a class="remove">X</a></li>');
});

$('.remove').click(function(){ 
 $(this).parent().hide('slow').remove();
});

Anyone shed any light on this, do I need to update the dom or something to get jQuery to recognize the appended elements?

+5  A: 

You need to use the new live API added in 1.3

http://docs.jquery.com/Events/live

If you can't use 1.3, there is a JQuery plugin for 1.2 called LiveQuery that works similarly.

pjb3
+1  A: 

Ah, I got bitten by this a few days ago. You will need to bind the event(s) to all new elements that are added after the ready handler is executed when the page loads. Interestingly, there is the excellent jQuery Live Query plugin that takes care of everything.

ayaz
A: 

you are trying to bind an event handler to an element type that doesn't exist. Use jQuery 1.3+ It has a new $.live() that can set up event handlers for elements that don't exist yet

Scott Evernden
+1  A: 

This is a normal behaviour. When you call a selector (e.g. $(".remove")), it's executed against current DOM. When your setup the "remove" event handler, it will be associated with existing items (1 and 2 in your example) but not with items created after that.

Fortunatly, a new function was recently added to jQuert : live. It will let you setup events that are associated with DOM elements added afterwards :

$('.remove').live("click", function(){ 
        $(this).parent().hide('slow').remove();
});
ybo
A: 

jQuery 1.3.x supports "live events": events can be bound to current and future elements that match the selector. You can achieve this by using the .live() method.

Kees de Kooter
A: 

While I would recommend using the latest version of jQuery, you can also do this without "live" events by creating the event somewhere in your desired namespace and binding the event on the items before you are done using them.

var removeClickFunction = function(ev) {
    $(this).parent().hide('slow').end().remove();
    ev.preventDefault();
};
$('.remove').click(removeClickFunction);

$('.add').click(function(ev) {
    $('#mylist').append($('<li>Item 3 </li>').append($('<a class="remove" href="#">new remove</a>').click(removeClickFunction)));
    ev.preventDefault();
});
patridge