user2958571
user2958571

Reputation: 133

jquery function for images created dynamically

I added images to the page dynamically now i need to add some function for this images. I need to add click event for each image.

this is the code that adds the images (its inside a table that is also created dynamically):

for (var i = 0; i < numOfCandidates; i++) {
    var url = "/images/user"+(i+1) + ".png";
    cell23 = $('<td width=cellWidth + "%" align="center" style="height:60%"></td>').html( '<img id="img'+(i+1)+'" src="' + url + '">');
    row23.append(cell23);
}

is there a way to add a click event with jquery for the images added?

Upvotes: 0

Views: 35

Answers (2)

Anton
Anton

Reputation: 32581

Give images a class when you create them and use event delegation .on()

$(document).on('click','.myClass',function(){
     //function
});

Documentation

Upvotes: 1

arun15thmay
arun15thmay

Reputation: 1062

 for (var i = 0; i < numOfCandidates; i++) {
      var url = "/images/user"+(i+1) + ".png";
      cell23 = $('<td width=cellWidth + "%" align="center" style="height:60%"></td>').html( '<img id="img'+(i+1)+'" src="' + url + '">');
      row23.append(cell23);
      $('#img'+(i+1)).click(function(){})
 }

Upvotes: 0

Related Questions