1

check this https://jsfiddle.net/qh2pfhjy/

I am create a div on the fly but click function doesn't work.

Any idea?

Also my code is:

$("#helloDiv").click(function(){
    alert("The paragraph was clicked.");
});

$(document.body).append('<div id="helloDiv">Edit me</div>');
Irene T.
  • 1,303
  • 2
  • 18
  • 37

1 Answers1

2

To bind events to dynamically created elements, update code like this.

From

$("#helloDiv").click(function(){
    alert("The paragraph was clicked.");
});

To

$(document).on("click", "#helloDiv", function(){
    alert("The paragraph was clicked.");
});

Make sure you replace document by whatever parent context you have that is a) not dynamically created and b) as close as possible to your dynamically added div.

For reference - http://api.jquery.com/on/

https://jsfiddle.net/qh2pfhjy/2/

connexo
  • 41,035
  • 12
  • 60
  • 87
Nikhil Aggarwal
  • 26,884
  • 3
  • 37
  • 53