jQuery – Click event doesn’t work on dynamically generated elements

The click() binding you’re using is called a “direct” binding which will only attach the handler to elements that already exist. It won’t get bound to elements created in the future. To do that, you’ll have create a “delegated” binding by using on():

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

Here’s what you’re looking for:

$("h2").on('click', 'p.test', function() {
    alert('you clicked a p.test element');
});

The above works for those using jQuery version 1.7+. If you’re using an older version, refer to the previous answer below
Try using live()

$("button").click(function(){
    $("h2").html("<p class='test'>click me</p>")
});   


$(".test").live('click', function(){
    alert('you clicked me!');
});

Or there’s a new-fangled way of doing it with delegate()

$("h2").delegate("p", "click", function(){
    alert('you clicked me again!');
});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s