0

I have seen 1 or two posts like this problem, but mine differs slightly, and the proposed fixes didn't work for me (usually a typo for them) In my case it is not a typo.

I am appending into a div with jQuery, creating a div inside of it on loadup.

When this div is clicked it launches into a method.

However, the selector will not work.

Here is the place where I append the data:

else if (isEquipped != true && data.archer.level == 0) {
    $("#locked-list").append(`
        <div id="archer-locked" class="archer-link"></div>
    `);
}

Here is the selector:

$("#archer-locked").on("click", e => {
  console.log("hmmm");
  if (e.target.className != "") {
    classView(e, false);
  }
});

Everything looks like it should inside the inspect console.

However, it is not triggering for some reason.

Nick
  • 565
  • 4
  • 19
William
  • 1,175
  • 2
  • 17
  • 32

1 Answers1

0

Listen for a click on the parent, then check against the child:

$("#locked-list").on("click", "#archer-locked", e => {...});
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • Awesome, thank you! IS there an explanation why this works and not the other way?? – William Apr 24 '19 at 09:15
  • 1
    @William Because when your code ran, `$("#archer-locked").on("click", e => {...})` was run immediately, and as there was no element that matched `#archer-locked`, jQuery discarded the listener. – Jack Bashford Apr 24 '19 at 09:16
  • Ohhh! Okay, I thought those things were dynamic and it would pick up on when there was a valid selector. Thanks again! – William Apr 24 '19 at 09:18
  • 1
    Nope - you need to attach the listener to the parent (as long as the parent is not dynamic) and then listen for a click on the dynamic element. – Jack Bashford Apr 24 '19 at 09:19
  • @William if my answer fixed your problem, please consider marking it as accepted. – Jack Bashford Apr 24 '19 at 09:27