Detection click on image

I am trying to load images dynamically and display them as shown below.

var uploader = $('#<%=uploader.ClientId%>').plupload('getUploader'); uploader.bind('FileUploaded', function (up, file, res) { $('#<%=thumbs.ClientId%>').append("<div id=" + file.id + "> <a href='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "'/> <img src='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "' width='70' height='55' data-full='Uploads/" + document.getElementById("<%=currentDirectory.ClientId%>").value + "/" + file.name + "'/></div>"); }); 

This is my markup:

  <div id="thumbs" class="imgContain" runat="server"> </div> 

If I do this on a div, it gives me a warning, but not on the image, but on the div:

  $('.imgContain').click(function () { alert('You Clicked Me'); }); 

And I tried using this method, but it gives me a warning not even on the div.

  $('.imgContain a').click(function () { alert('You Clicked Me'); }); 

So how do I do this?

+7
source share
4 answers

you should use the on method

  $('.imgContain').on("click","a,img", function (e) { e.preventDefault(); alert('You Clicked Me'); }); 
+10
source

It's a little tricky to find out what your DOM looks like, but I think you are adding images to a div with the .imgContain class. If you want to add a click event for these images, you can do something like this:

 $('.imgContain').on("click", "img", function () { alert('You Clicked Me'); }); 

I suppose you add images dynamically, you should use the .on() method to bind the click event, instead of using .click() .

Note If for some reason you are using a previous version of jQuery, you can change .on() instead of .live() .

+4
source

For the <a> anchors you added, you will need to use .live() to attach a click event to it:

  $('.imgContain a').live("click", function (event) { event.preventDefault(); alert('You Clicked Me'); }); 
+2
source

Learn how to live in jQuery. and use it in your code.

jQuery version 1.4.1 and higher.

as elements are placed on html dynamically after loading your page. The click function is not bound.

0
source

All Articles