1

I know that similar questions are being asked (like here) but, being a jQuery noob, I still can not attach a click listener to an a element within a li where the whole ul.li.a is dynamically appended to the DOM like this.

<div id="users-col">
  <!-- dynamically appended --> 
  <ul id="users-list">
       <li>
          <a class="user" id="Alice">Alice</a>
       </li>
       <li>
          <a class="user" id="Bob">Bob</a>
       </li>
  </ul>
   <!-- END dynamically appended --> 
</div>

Here is a (one of the many) jQuery functions that I have tried:

$('#users-col ul.li.a').on('click', '.user', (function () {
  console.log('user clicked:', this.id); 
});

How can I fix this?

Karlom
  • 13,323
  • 27
  • 72
  • 116

3 Answers3

5

You need to bind the event on element that is available (not added dynamically)

$('#users-col').on('click', 'a.user', (function () {
  console.log('user clicked:', this.id); 
});

For reference, jQuery.on

Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

in such case you must hook an event with parent of dynamically created children:

$('#users-col').on('click', 'a.user',        (function () { 
console.log('click bound'); 
});
Raphael
  • 770
  • 1
  • 7
  • 23
0

For convenience sake and reuse, I leave the first field just directly tied to the document:

$(document).on('click', '.user', (function () {
  console.log('user clicked:', this.id);
}));
<div id="users-col">
    <!-- dynamically appended -->
    <ul id="users-list">
        <li>
            <a class="user" id="Alice">Alice</a>
        </li>
        <li>
            <a class="user" id="Bob">Bob</a>
        </li>
    </ul>
    <!-- END dynamically appended -->
</div>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    </script>

The listener is directly tied to the document vice the class, so now it is very easy to reuse this class dynamically across your entire document.

Daniel Lord
  • 754
  • 5
  • 18
  • I had try this. Its problem was that it was triggered for whatever click on the page. – Karlom Jun 06 '18 at 12:35
  • @Karlom no, it should only trigger for tags with class="user". Unless your body contains class user, it shouldn't trigger for every click. – Daniel Lord Jun 06 '18 at 12:50