-1

I've a HTML page where I'm adding an icon file to DIVs dynamically. This image serves as close icon and has a predefined class, say, 'close'. To this class I've attached the click event like

$('.close').click(function({
     alert('You chose to delete this image');
});

this works fine for the script that is loaded on page load. However, when I attach the same icon to other DIVs, the click event doesn't seem to trigger. There's no error in firebug. I don't know what's wrong!

Sayed
  • 601
  • 6
  • 21

2 Answers2

4

Delegate on document or the closest static element

$(document).on('click', '.close', function () {
    alert("You chose to delete this image");
});
Anton
  • 32,245
  • 5
  • 44
  • 54
1

You need to do event delegation:

$(document).on('click', '.close', function () {
    //rest of the code

}
Harry
  • 87,580
  • 25
  • 202
  • 214