0

Click event does not works with copied HTML?

 <ul class="dir">//the given ul
 <li>  <img class="thumb" src="1.jpg" >  </li>
 <li>  <img class="thumb" src="2.jpg" >  </li>
 <li>  <img class="thumb" src="3.jpg" >  </li>
 <li>  <img class="thumb" src="4.jpg" >  </li>
 <li>  <img class="thumb" src="5.jpg" >  </li>
 <li>  <img class="thumb" src="6.jpg" >  </li>
 <li>  <img class="thumb" src="7.jpg" >  </li>
 </ul>
 <ul class="copy"></ul> //copied ul
 <script>
 $(function(){
 $(".copy").html($(".dir").html());
 $(".thumb").click(function(){
 alert("It works only on the .dir's thumb not on .copy's thumb .. why?");
 }
 );
 }
 </script>
Cyclonecode
  • 29,115
  • 11
  • 72
  • 93

1 Answers1

1

You have to use event-delegation

$(document).on('click', '.thumb', function(){
   alert("This works every even if copied");
});

for it to work. Just .click will only attach the handler to the elements, which existed at the point of declaring the handler.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95