0

I need to bind click event for a anchor tag which is created dynamically.

Example:

$.fn.ccfn = function(){
$(".alreadyavailabledom").click(function(){
   $("<a class="dynamicallycreated"></a>");
})
//i am trying like below, but not working

$(".dynamicallycreated").click(function(){
alert("not getting alert why?")
})

}

It is written as a plugin code, i tried with on, live etc. Not working.

raj
  • 543
  • 1
  • 6
  • 11
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Blazemonger Mar 12 '14 at 14:13

2 Answers2

1

you should use event delegation for that

$(document).on("click",".alreadyavailabledom",function(){
   //some operation
});

It helps you to attach handlers for the future elements

Anoop Joshi
  • 24,460
  • 8
  • 28
  • 49
0

Use event delegation

$(document).on('click','.dynamicallycreated',function(){
    alert("not getting alert why?")
})

or bind the click when creating element

$.fn.ccfn = function () {
    $(".alreadyavailabledom").click(function () {
        $('<a>', {
            html: "anchor",
            class: "dynamicallycreated",
            click: function () {
                alert("clicked anchor");
            }
        }).appendTo('#myElement');
    })
}
Anton
  • 30,499
  • 5
  • 42
  • 54