Jquery $("img").click(function() selector not working

Stefan picture Stefan · Sep 29, 2014 · Viewed 62.4k times · Source

For some reason when I click on an image with this JQuery code the alert screen doesn't show up.

HTML:

<div id="example1">
 <div>
  <div>
   <div class="user">
    <img class="Image" src="images/image.jpg">
   </div>
  </div>
 </div>
</div>

Javascript:

$(document).ready(function(){
 $("img").click(function(){
  alert("it works!");
 });
});

I cant figure out why this isn't working I included the jquery library and the <script> tag is under the div

Answer

electrophanteau picture electrophanteau · Sep 29, 2014

the img isn't in the DOM when your event handler is registered. you can use $('body').on('click','img',function(){alert('it works');})