Skip to content

Instantly share code, notes, and snippets.

@hemantajax
Created December 4, 2012 08:38
Show Gist options
  • Save hemantajax/4201871 to your computer and use it in GitHub Desktop.
Save hemantajax/4201871 to your computer and use it in GitHub Desktop.
Inserting Items in a Sorted List with jQuery
<!doctype html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<style>
ul,li{
margin: 0;
padding: 0;
list-style: none;
}
li{
margin-bottom: 2px;
padding: 4px;
background: #eee;
border: 1px solid #999;
}
</style>
</head>
<body>
<ul id="list">
<li id="allFilter" class="active">All</li>
<li id="479">11</li>
<li id="478">1Sa</li>
<li id="474">AA</li>
<li id="476">BB</li>
<li id="448">T3</li>
<li id="477">UU</li>
</ul>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
(function(){
var newItem = "Item to insert";
// Grab all the existing items
var sortedList = new Array();
$("#list").find("li").not("#allFilter").each(function(i, item) {
sortedList.push($(this).html().toLowerCase());
})
var initialLength = sortedList.length;
// Add the new item and sort the list
sortedList.push(newItem.toLowerCase());
sortedList.sort();
// Then find where the item ended up
var i = $.inArray(newItem.toLowerCase(), sortedList);
// If the item ends up at the end of the list, just append it
if(i == initialLength) {
$("#list").append("<li>" + newItem + "</li>");
// Otherwise, insert it before the element it’s replacing
} else {
$($("#list").find("li")[i]).after("<li>" + newItem + "</li>");
}
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment