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 to 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.

Source

Here's what you're looking for:

var counter = 0;

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

// With on():

$("h2").on("click", "p.test", function(){
    alert($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<h2></h2>
<button>generate new element</button>

The above works for those using jQuery version 1.7+. If you're using an older version, refer to the previous answer below.


Previous Answer:

Try using live():

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


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

Worked for me. Tried it with jsFiddle.

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

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

An updated jsFiddle.


Use the .on() method with delegated events

$('#staticParent').on('click', '.dynamicElement', function() {
    // Do something on an existent or future .dynamicElement
});

The .on() method allows you to delegate any desired event handler to:
current elements or future elements added to the DOM at a later time.

P.S: Don't use .live()! From jQuery 1.7+ the .live() method is deprecated.


Reason:

In jQuery, Click() event binds the element only if the particular element exist in the Html code(after page loads).

It won't consider the future elements which are created dynamically(Future element). Dynamic elements are created with the help of javascript or jquery(not in Html).

So the normal click event won't fire on the dynamic element.

Solution :

To overcome this we should use on() function. on() Can delegate the event for both current and future elements.

delegate(),live() and on() functions have the advantages over the DOM elements.

delegate() and live() are deprecated(Don't use these).

on can only trigger both the existing and future elements.

on can consider all the elements which are present on the whole page.

You should use on function to trigger the event on dynamically(future) created elements.

Remove the code from $(document).ready:

$(".test").click(function(){

  alert();

});

Change into:

$(document).on('click','.test',function(){

  alert('Clicked');

});

Tags:

Events

Jquery