-1

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/

Snedden27
  • 1,870
  • 7
  • 32
  • 60
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Manish Sep 08 '16 at 03:50

3 Answers3

3

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();
});
Derek Story
  • 9,518
  • 1
  • 24
  • 34
1

If you want to bind an event listener to a dynamically created element you need to use jQuery.on, like this $("#userList").on("click", "li", function(){ ... });.

Hope it helps.

Bla...
  • 7,228
  • 7
  • 27
  • 46
1

Using 'on' or not does not really matter, as long as not defining function on the fly:

$('#userList li').click(relocLi);
$('#sharedUsers li').click(relocLi);

function relocLi() {
  if ($(this).attr('title') == "Add user") {
    $(this).attr('title', 'Remove user');
    $("#sharedUsers ul").append($(this));
  } else {
    $(this).attr('title', 'Add user');
    $("#userList ul").append($(this));
  }
}
Don Flash
  • 11
  • 3