0

I want to use .on on dynamically created elements... Although its not working, and yes I am using a selector :)

$(".metadata").on("click", "i.icon-remove", function () {
    console.log("what");
    $(this).parent(".metadata").slideUp(function () { $(this).remove(); });
});

This works perfectly for existing content, but not for anything thats dynamically created. Both initial and dynamic content use the exact same creation method so I know their signatures are the same, any ideas?

Here is my HTML as it stands, the first item is present in the HTML, the second is dynamically created

<div class="metadata">
    <input type="text" value="" style="width: 200px;">
    <i class="icon-remove"></i>
</div>
<div class="metadata" style="">
    <input type="text" maxlength="100" style="width: 200px;">
    <i class="icon-remove"></i>
</div>
Chris
  • 26,744
  • 48
  • 193
  • 345
  • whether the `metadata` element also is dynamically create – Arun P Johny Jan 02 '14 at 17:11
  • 6
    I've lost count of how many times this question was asked on StackOverflow. – Pavlo Jan 02 '14 at 17:14
  • True, I went through about 5 of them before I posted, however in almost every one the problem was due to a missing selector, not because I hadnt anchored it on a static parent element... Also, does this perhaps not describe a barrier in understanding `on` - I never had a problem before :) – Chris Jan 03 '14 at 08:53

2 Answers2

3

Try this

$(document).on("click", ".metadata i.icon-remove", function () {
    console.log("what");
    $(this).parent(".metadata").slideUp(function () { $(this).remove(); });
});
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 4
    To explain further, event delegation must start with an element that's available on page load. It doesn't have to be `body`, but some available ancestor of your element. – isherwood Jan 02 '14 at 17:12
2

As an addendum to Pranav's answer, avoid if at all possible doing delegated events off of $(document) - that results in all events that happen anywhere in the page being inspected for matches to your selector.

Far better would be to use a more targeted selection that exists on the page from the start. Something like

$('#otherDivThatsThere').on("click", "i.icon-remove", function () {
    console.log("what");
    $(this).parent(".metadata").slideUp(function () { $(this).remove(); });
});

Where, again, #otherDivThatsThere is already in your dom at the moment that line of code is run.

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393