Question

Quick overview: I have two divs with their respective unordered lists. The jQuery is supposed to allow the clicked items to move from one div to the next. That functionality seems to work only once per list item. When I click on the list items after they've moved they do not revert back to their original div location. I've looked at the html in firebug and it's formatted correctly after the moves, but jQuery is no longer able to manipulate them. Help!

the jQuery

$('#one ul li').click(function () {
    var value = $(this).text();
    var id = $(this).attr('id');
    $('#two ul').append('<li id="'+ id +'">' + value + '</li>');
    $(this).remove();
});
$('#two ul li').click(function () {
    var value = $(this).text();
    var id = $(this).attr('id');
    $('#one ul').append('<li id="'+ id +'">' + value + '</li>');
    $(this).remove();
});

the html are two lists imbedded in divs

<div id="one">
   <ul>
      <li id="1">One</li>
      <li id="2">Two</li>
   </ul>
</div>

<div id="two">
   <ul>
      <li id="3">Three</li>
      <li id="4">Four</li>
   </ul>
</div>

Was it helpful?

Solution

Instead of binding to click on the items directly as you are doing now:

$('#one ul li').click(function(){...})

This applies when the script is loading only to contact that is matched then. Since your LI is added later (dynamically) no event is bound on that one. You can use the .on() jQuery function to bind to a parent element specifying a scope, which will apply to any element loaded in the future:

$("#one").on("click", "ul li", function(){...})

The difference is the event is bound to #one but applies to any ul li inside it (present and future).

https://api.jquery.com/on/

OTHER TIPS

remove() removes the element from the DOM element and also remove its event handlers and any data associated with the DOM element. What you are doing is removing the DOM element clicked (this also removes the event handlers defined on it), then making a new one (the newly created element has no event handler defined on it) and appending that created element to the list element. You should instead just use append(). When you append() elements that are already part of the document, those elements will be moved to their new location.

This is a better solution:

$('#one ul li').click(function () {
  var elem = $(this);
  $('#two ul').append(elem); //move element to new location
});

$('#two ul li').click(function () {
  var elem = $(this);
  $('#one ul').append(elem);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top