0

I am trying to add an image tag dynamically

  var img = $('<img id="dynamic" class="removed">'); //Equivalent: $(document.createElement('img'))
            img.attr('alt', "remove");
            imageForm.append(img)

and where ever I have appended this one I want a click function

so I have written

$('.removed').on('click', function (e) {
    console.log("e", e);
    e.preventDefault();
});

But the event is not getting triggered. what should I do to fix this?

Govind Samrow
  • 9,981
  • 13
  • 53
  • 90
vishnuprasad kv
  • 990
  • 5
  • 22
  • 46

2 Answers2

1

For dynamically created elements you need to attach the event via $(document) and pass the selectors for which you want to attach the handler

$(document).on('click', '.removed', function (e) {
    console.log("e", e);
    e.preventDefault();
});
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
1

The click function you have written will not find any element with class = .removed since you are adding the image dynamically. For such case you need to bind the function to an already existing element i.e. static element. You may bind the function to the parent static element of the image or just bind it to document. So your code becomes :

$(document).on('click','.removed',function(e){ 
    e.preventDefault();
    console.log("e",e);
});