AlexAstanin
AlexAstanin

Reputation: 363

How to bind click event to element is created on click event?

I have script like this:

$(document).ready(function() {
    $('.button').click(function() {
       var button = document.createElement('button');
       $(button).addClass('button');
       $(button).html('Button');
       $(button).appendTo('.container');
    });
});

Example: jsfiddle

Buttons is created by button click hasn't click event. How to attach this event to have possibility to create buttons with using of any button?

Upvotes: 1

Views: 61

Answers (1)

T J
T J

Reputation: 43166

You need to delegate the event handler to work with dynamically generated elements.

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

You can use on() method to delegate the handler as follows:

$(document).on("click",".button",function() {})

Updated Fiddle

Upvotes: 4

Related Questions