1

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?

Sujoy
  • 1,186
  • 1
  • 9
  • 12
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Tibrogargan Nov 05 '16 at 06:20

3 Answers3

2

you can use below code to bind event

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

this call dynamic binding.

Veer
  • 6,046
  • 1
  • 14
  • 12
1

Delegate it. Attach the listener to its parent and let the event bubbles.

$("body").on('click', '.imageThumbnails', function() {...}

ltamajs
  • 1,231
  • 11
  • 15
0

See Its working.. You are not closing your clicking function .`

$(document).ready(function () {
$(".imageThumbnails").click(function() {...})
})

`

(function () {
  $('body').append('<img class="imageThumbnails" src="some.png" alt="submit" >')
  
  })()

$(document).ready(function () {
$('.imageThumbnails').click(function () {
  
  console.log('work');
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
prasanth
  • 22,145
  • 4
  • 29
  • 53