Sujoy Sujoy - 1 year ago 66
Ajax Question

how to use a dynamically added html class inside ajax

I am trying to pull all images from a folder on a page. Then I have added html class to the '.append' function against an element of jquery inside ajax. Now I want to use the class outside ajax in another function. But it seems the class was local and hence not defined outside ajax. Can you please tell me how to solve this? My code -

/* html code */
<div id="imageWrapper">

<div id="spanImage"></div>


var folder = "images/";
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
$("#spanImage").append( "<img src='"+ folder + val +"' class='imageThumbnails'>");

/* I have added class = 'imageThumbnails' dynamically to each image appended. Now I would like to use the class to work on individual image to make them pop up
$(".imageThumbnails").click(function() {...}


This is not working as 'imageThumbnails' is not recognized by the system as a valid class. Can you please help?

Answer Source

you can use below code to bind event

$(document).on("click",".imageThumbnails",function() {...});

this call dynamic binding.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download