I have two lists of links. I have it such that when a user clicks on a link on either list, it is moved to the other list. Very quickly the lists become unorganised so I would like to keep them organised by an ID.
What I want then is when a user clicks the link, it will search in the list for the last element whose data-id
is less than the link that was clicked. I would then insert the element after that.
Now, what I am really interested in is the most efficient (code wise) way of doing this with jQuery. I understand I can do this using $(".added").each()
but it seems very clunky. Is there a better way using 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>
The 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");
}
});
.each()
or some other variant. One optimization I'd suggest is that since you're always inserting in order anyway, you can break the iteration loop once you've come across an element that has adata-id
value greater than your insertion element. – Imperishable