Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect click on an image

I am trying to load images dynamiaclly and displaying 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 way on the div it gives me an alert but not on the image but on the div:

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

And I have tried using this way but it dosent give me any alert not even on the div also.

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

So how do I do this?

like image 613
coder Avatar asked Feb 05 '12 10:02

coder


3 Answers

you should use the on method

 $('.imgContain').on("click","a,img", function (e) {
      e.preventDefault();
      alert('You Clicked Me');
 });
like image 174
Royi Namir Avatar answered Nov 01 '22 21:11

Royi Namir


It's a little hard to know exactly what your DOM looks like, but I guess you add the images to the div with class .imgContain. If you want to add a click event to those images you could do something like this:

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

As I believe you are adding the images dynamically, you should use the .on() method to bind the click event, instead of using .click().

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

like image 34
Christofer Eliasson Avatar answered Nov 01 '22 19:11

Christofer Eliasson


For the anchors <a>s that you appended, youwill need to use .live() in order to attach to it the click event like:

 $('.imgContain a').live("click", function (event) {
      event.preventDefault();
      alert('You Clicked Me');
 });
like image 43
Mahmoud Gamal Avatar answered Nov 01 '22 19:11

Mahmoud Gamal