compcentral
compcentral

Reputation: 1185

Dynamically added javascript is not working, but static code works fine?

Here is what I'm doing... I have a textbox that users type something in and click an add icon. This fires some jquery code that adds the item they typed into a span within a "content" div. The generated code has a delete icon that appears on hover and when clicked it should make the span disappear. This works if the code is on the page already (before document load) but if it's dynamically created, it breaks the delete on click functionality.

Here is a JSfiddle so you can see it in action: http://jsfiddle.net/WF32y/

What can I do to fix this? I essentially want to do what happens on here (stackoverflow.com) when you enter tags to a new question.

Upvotes: 1

Views: 103

Answers (2)

John Skoubourdis
John Skoubourdis

Reputation: 3259

You can easily do it with delegate. In your case:

  $('#container').delegate('a.delete','click', function(e) {
    e.preventDefault();
    taskID = $(this).closest('.task')[0].id;
    $(this).closest('.task').fadeTo(300, 0, function() {
        $(this).animate({
            width: 0
        }, 200, function() {
            $(this).remove();
        });
    });
});

And by the way FYI:

// jQuery version 1.4.3+
$('#container').delegate('a.delete'...

// jQuery 1.7+
$('#container').on('click', 'a.delete', function(e) { 

it is faster and more propery way than:

$(document).on('a.delete'...

or:

$('body').delegate('a.delete'...

or:

$(document).delegate('a.delete'...

Upvotes: 1

Fabrício Matté
Fabrício Matté

Reputation: 70139

Use event delegation for dynamically added elements by changing this:

$('a.delete').on('click', function(e) {

Into this:

$(document).on('click', 'a.delete', function(e) {

Fiddle

.on() Direct and delegated events reference

Also, concerning performance, you can attach the handler to a closer ancestor of the dynamically added elements than the document (e.g. a static wrapper element).

Upvotes: 5

Related Questions