Sujoy Sujoy - 1 month ago 8
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 */
<body>
<div id="imageWrapper">

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

</div>

<script>
var folder = "images/";
$.ajax({
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() {...}

</script>
</body>


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

Answer

you can use below code to bind event

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

this call dynamic binding.

Comments