Manish Basdeo
Manish Basdeo

Reputation: 6269

Trigger on dynamically created element

I am creating dynamic elements and upon click of a another button, a click event on the dynamically generated element need to be executed. I know on() jquery method has such a functionality but do not know how to apply in my context. I would be glad if someone could help.

HTML Code:

<h2></h2>
<button>generate new element</button>
<p class="generateEvent">Event</p>

My jQuery Code:

$(function(){

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

    $('.generateEvent').click(function(){
        $("p").trigger("click", function(){
            alert('you clicked me again!');
        });
    });
});
// Method two: 

http://jsfiddle.net/PzSYM/399/

Upvotes: 0

Views: 2565

Answers (2)

nix
nix

Reputation: 3302

You can use on() by binding the event to the target's parent container which is already on the page when you first load the page. Like this way:

$('#parent').on('click','.target',function(){
   //do something..
});

Upvotes: 3

Laughing
Laughing

Reputation: 211

try this,

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

http://jsfiddle.net/sCgCj/

Upvotes: -1

Related Questions