jquery bind to dynamically added elements code example

Example 1: javascript bind event to created element

// bind click handler to element that is added later/dynamically
document.addEventListener('click', function(e){
    if(e.target && e.target.id== 'myDynamicallyAddedElementID'){
         //do something
    }
});

//Alternatively, if your using jQuery:
$(document).on('click','#myDynamicallyAddedElementID',function(){
    //do something
});

Example 2: jquery dynamic event handling

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());
});