Reputation: 179
How would I go about removing an object say from an unordered list and add it to another list while keeping its location? I know i can set the original item to hide() but then that leaves a small space where the item use to appear. Say i have a list A and B, if a user clicks on an item in A it needs to be added to B and removed from A. If they now click on a button to remove it from B and back to A, i want to have it displayed in the same spot it originally did. I know i can add it via append() but that won't put it in the same location. Thoughts anyone?
Upvotes: 2
Views: 1444
Reputation: 101604
Heres my bid:
HTML:
<ul id="list-1">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
<ul id="list-2"></ul>
JavaScript:
var $list1 = $('#list-1');
var $list2 = $('#list-2');
$list1.children('li').each(function(i,e){
var ulId = $(this).closest('ul').attr('id');
$(this).attr('li-id',ulId+'_'+i);
}).click(function(e){
if ($list2.find('li[li-id="'+$(this).attr('li-id')+'"]').length == 0){
var liClone = $(this).clone();
liClone.click(function(e){
var elId = $(this).attr('li-id');
$list1.find('li[li-id="'+elId+'"]').show();
$(this).remove();
});
$list2.append(liClone);
}
$(this).hide();
});
Fiddle: http://www.jsfiddle.net/vgx23/1/
Upvotes: 1
Reputation: 2447
You could use .clone? so:
<ul id="firstlist">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
<ul id="secondlist">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
the jquery:
var object = $('#firstlist > li :last ').clone();
$('#secondlist').append(object);
$('#firstlist > li :last ').destroy();
Obviously you can swap this round to add it to the first list, but to get the position you could use a number of ways, I would probably do:
$('#firstlist').children('li').each(function(i){
});
and use "i" to get the position. you can append after a given object to so:
$('#firstlist').children('li').each(function(i)
{ if(i== 4){ $(this).append(object).after(this) }
Upvotes: 1