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,393
  • 2
  • 20
  • 40

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
  • 53,704
  • 14
  • 91
  • 128
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59