0

On page load, I have a search box that, once used, populates a div with multiple images. The javascript from the search uses this function to append all images into the div

   function appendSomeItems(url, id, name, style) {
        return '<div><div class="md-card md-card-hover">         <div id="getImage" class="gallery_grid_item md-card-content"> <img class ="uk-align-center imageClick"></a>                               <div class="gallery_grid_image_caption">                                   <span class="gallery_image_title uk-text-truncate">' + name + '</span> <span>' + style + '</span> </div></div></div></div>';
    }

This works perfectly. Now I'm trying to make it so that when I click any one of the images it triggers an action (in this case a console log)

    $('.imageClick').click(function handleImage() {
        console.log(good);
    });

However, it does nothing. No error but no console log.

What am I doing wrong here?

Geoff_S
  • 4,917
  • 7
  • 43
  • 133
  • I think you need to add the handler after the image is attached to the dom. ie run ``` $('.imageClick').click(function handleImage() { console.log(good); });``` after the images are added – Oliver Mar 21 '19 at 00:44
  • is good a variable? If not it should be wrapped in quotes console.log('good'); –  Mar 21 '19 at 00:45

3 Answers3

1

You need to use event-delegation in order to bind an event to dynamically created elements:

This approach uses document as the parent element, however, a good practice is to use the closest parent element.

$(document).on('click', '.imageClick', function handleImage() {
    console.log(good);
});
Ele
  • 33,468
  • 7
  • 37
  • 75
1

Try with .on() to attach event on dynamically created element. This will allow attaching the event to the elements that are added to the body at a later time:

$('body').on('click', '.imageClick' function handleImage() {
  console.log(good);
});
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

The problem is that you are calling $(".imageClick").click() before you dynamically create the items.

This means that jQuery doesn't actually bind the click listener to the items, since when $(".imageClick").click() is run, the elements don't actually exist yet.

Try this:

$("body").on("click", ".imageClick", function handleImage() {
    console.log("good");
});

Also see this post for more information: In jQuery, how to attach events to dynamic html elements?

Nathan
  • 1,321
  • 1
  • 18
  • 32