Snedden27 Snedden27 - 3 months ago 15
CSS Question

Dynamically adding event listener in html

I have two ULs in HTML ,one for user and one for shared user.

<div class="container">

<div id="userList" style=" ;width:45%;margin:10px;display:inline-block;vertical-align: top;">
<span>Users</span>
<ul class="usersUL">
<li title="Add user"><a href="#">user1</a></li>
<li title="Add user"><a href="#">user2</a></li>
</ul>
</div>

<div id="sharedUsers"style="width:45%;margin:10px;display:inline-block;vertical-align: top;">
<span>Shared Users</span>
<ul class="usersUL" >

</ul>
</div>
</div>


I want to add the li in UL one to the second list on user click and vice versa. The way I have done this is like so

//add to shared users from userslist
$("#userList li").click(function(){

$("#sharedUsers ul").append('<li title="Remove user">'+$(this).html()+'</li>');

//add to users list from shared users
$("#sharedUsers li").click(function(){
$("#userList ul").append('<li title="Add user">'+$(this).html()+'</li>');
$(this).remove();
});
$(this).remove();
});


I know what I doing wrong , I am not adding new event listener once the list item to sent back to the first UL from the second UL.But I am struggling to find the best way I can do this.

Here is the js fiddle: https://jsfiddle.net/4n7Ly4r2/

Answer

You can't nest a click event within a click event. Also, you need to bind the click event to the dynamic content using on():

JS Fiddle

$(document).on('click', '#userList li', function() {    
  $("#sharedUsers ul").append('<li title="Remove user">' + $(this).html() + '</li>');      
  $(this).remove();
});

$(document).on('click', '#sharedUsers li', function() {    
  $("#userList ul").append('<li title="Add user">' + $(this).html() + '</li>');
  $(this).remove();
});