I have two lists of links. I have such that when a user clicks on a link in any list, he moves to another list. Lists get disorganized very quickly, so I would like them to be organized using an identifier.
What I want, when the user clicks on the link, will search the list for the last element whose data-id
is less than the link. Then I insert the item after that.
Now, what really interests me is the most efficient (code wise) way to do this with jQuery. I understand that I can do this with $(".added").each()
, but that seems very awkward. Is there a better way to use selectors or something else?
<div class="available"> <h2>Available Groups</h2> <a href="" data-id="1">Group 1<span>Add</span></a> <a href="" data-id="2">Group 2<span>Add</span></a> <a href="" data-id="3">Group 3<span>Add</span></a> <a href="" data-id="4">Group 4<span>Add</span></a> <a href="" data-id="5">Group 5<span>Add</span></a> </div> <div class="added"> <h2>Added Groups</h2> </div>
Current implementation:
$(".available a").on("click",function(){ var myID = parseInt($(this).data("id")); var alist = $(".added a"); if (alist.length > 0) { var nodeToInsertAfter; $(".added a").each(function () { if (parseInt($(this).data("id")) < myID) nodeToInsertAfter = $(this) }); if (nodeToInsertAfter) $(this).insertAfter(nodeToInsertAfter); else $(this).prependTo(".added"); } else { $(this).appendTo(".added"); } });
Chris source share