afro360
afro360

Reputation: 620

HTML added with .append() is not triggering events

I have some jQuery appending HTML from a PHP script.

jQuery

$.ajax({
    type: "POST",
    url: "newPage.php",
    data: data,
    cache: false,
    success: function(html)
    {
        $('.item1 ul').append(html);
    }
});

PHP

    echo"<li><a href=\"#\">".$pages["title"]."<img src=\"images/delete.jpeg\" class=\"delete del-page\" id=".$pages["pages_id"]." title=\"Delete Page\"/><img src=".$state." class=\"page-state\" id=".$pages["pages_id"]." title=\"Page On\"/></a></li>";

After appending, no jQuery events work on the new HTML.

Upvotes: 3

Views: 1088

Answers (2)

jondavidjohn
jondavidjohn

Reputation: 62392

You need to delegate your events with .on()

You can read specifically about this here

But basically you need to attach the listener higher up in the DOM heirarchy.

so instead of this...

$('.selector').on('event', function(e) {...});

do this

$('.item1 ul').on('event', '.selector', function(e) {...});

Why?

This works because the dynamic elements that are not yet on the page when you bind the events, still fire the events, they just don't have the handlers.

Thanks to event bubbling all DOM elements up the tree will hear their descendant's events (unless propagation has been stopped), and can act on them accordingly.

In this example, when '.item1 ul' hears that an 'event' has been triggered from one of it's child elements, if it was '.selector' that triggered it, the handler will fire.

Upvotes: 5

Blender
Blender

Reputation: 298166

You're probably binding your events to the elements:

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

This works only if the $('button') selector returns the elements you want. Your problem is that the selector is called once. It won't update to account for elements that were created after your selector has been called.

You should use the event delegation syntax to bind the event to an already-present parent element:

$('#parent').on('click', 'button', function() {
    ...
});

That way, when the #parent receives a click event, it'll look for elements matching button and pass the event off to them.

Upvotes: 4

Related Questions