-1

I have this code below. As you can guess, when I press on "foobar", a new element is added. The problem: when I click on the the new element nothing happens, why? Im using jQuery 2.1.

<div>
  <span>foobar</span>
</div>

<script type="text/javascript">
$("span").on('click', function() {
   $(this).clone().appendTo('div').addClass('new');
   alert("click on first element"); 
});
$(".new").on('click', function() {
   alert("click on second element"); 
});
</script>
tirenweb
  • 30,963
  • 73
  • 183
  • 303

3 Answers3

1

Two Things

1)You have not added the class correctly to cloned element.

2)You will also need event delegation to attach event to dynamically added element.

$("span").on('click', function() {
  $(this).clone().addClass('new').appendTo('div');
  alert("click on first element"); 
});

$("div").on('click','.new', function() {
 alert("click on second element"); 
});

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

bind click handler to dynamically added elements using below code

$(document).on('click',"div.new", function() {
   alert("click on second element"); 
});
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
0

Please try below code as the span is dynamically added you need to use event delegation :-

$(document).ready(function(){
   $("span").on('click', function() {
   $(this).clone().appendTo('div').addClass('new');
   alert("click on first element"); 
});
$("div").on('click', ".new", function() {
   alert("click on second element"); 
});
});

Demo :-

http://jsfiddle.net/DXQ5j/31/

Neel
  • 11,625
  • 3
  • 43
  • 61