HomTom
HomTom

Reputation: 598

jQuery: Moving Li elements?

I'm wrting following jQuery script which a click on a Li in the left div moves it to the right div.

$(document).ready(function(){

   $('.left ul li').click(function(){
      var toAdd = $(this).html();
      $('.right ul').append('<li>' + toAdd + '</li>');
   });

    $(document).on('click', '.left ul li', function(){
        $(this).remove();
    });

});

It works perfectly. However if I try to do the same for the Li elements in the left div, so that after ckicking them they move to the left div, it doesnt work.

$(document).ready(function(){

   $('.left ul li').click(function(){
      var toAdd = $(this).html();
      $('.right ul').append('<li>' + toAdd + '</li>');
    });

    $(document).on('click', '.left ul li', function(){
        $(this).remove();
    });

  $('.right ul li').click(function(){
      var toAdd = $(this).html();
      $('.left ul').append('<li>' + toAdd + '</li>');
    });

  $(document).on('click', '.right ul li', function(){
        $(this).remove();
    });

});

What I'm doing wrong?

This is the codepen link:

http://codepen.io/itsthomas/pen/hIfLD

Thanks for your help.

Upvotes: 0

Views: 620

Answers (1)

Yogesh
Yogesh

Reputation: 3482

You cannot bind event to element that do not exists.

$(document).ready(function(){   
    $(document).on('click', '.left ul li', function(){
        $(this).remove();
        var toAdd = $(this).html();
        $('.right ul').append('<li>' + toAdd + '</li>');
    });  

    $(document).on('click', '.right ul li', function(){
        $(this).remove();
        var toAdd = $(this).html();
        $('.left ul').append('<li>' + toAdd + '</li>');
    });  
});

Upvotes: 2

Related Questions