My html5, css, javascript program will be a day calendar. Clicking on the button of an event will bring up the details of that event. Right now, I have a days worth of events in the order they were entered. I’m stuck trying to sort an unordered list of buttons based on their id. Here you can see how each ul button is created. Values come from an indexedDB.
function renderTodo(row) {
var todos = document.getElementById("todoItems");
var li1 = document.createElement("li");
var name = document.createTextNode(row.name);
var li2 = document.createElement("li");
var time = document.createTextNode(row.time);
var btn = document.createElement("BUTTON")
var a = document.createElement("a");
var li = document.createElement("li");
a.addEventListener("click", function() {
helicopter.indexedDB.deleteEvent(row.timeStamp);
}, false);
a.textContent = " [Delete]";
li1.appendChild(name);
li2.appendChild(time);
btn.onclick=viewEvent;
btn.id=row.parent;
btn.row = row;
btn.appendChild(li1);
btn.appendChild(li2);
li.appendChild(btn);
li.appendChild(a);
li.id = row.time;
todos.appendChild(li)
sortUnorderedList(todos);
}
In other words, the finished product looks something like this.
ul-button2-[delete]
ul-button1-[delete]
ul-button3-[delete]
When I convert the list to array, it drops the button and only keeps the two li values. I’ve tried a few things to no success (see below). Should I drop the button idea and just use CSS to give the same look or is there a good way to sort the buttons.
function sortUnorderedList(ul) {
//if(typeof ul == "string")
//ul = document.getElementById(ul);
// Idiot-proof, remove if you want
if(!ul) {
alert("The UL object is null!");
return;
}
// Get the list items and setup an array for sorting
var lis = ul.getElementsByTagName("LI");
var ali = Array.lis;
ali.sort(liSort);
ul.innerHTML = "";
// Populate the array
for(var i = 0, j = lis.length; i < 2; i++)
ul.appendChild(ali[i]);
// Sort it
//vals.sort(liSort);
//vals.reverse();
// Change the list on the page
//for(var i = 0, l = lis.length; i < l; i++)
//lis[i].innerHTML = vals[i];
}
function liSort(one, two) {
//alert(one.id + " - " two.id);
return one.id - two.id;
}
1.) Because the
lis (which should be sorted) have sub-lis, it will be better to select them by class (which is available with html5); so add a class with following line afterli.id = row.time;:2.) In the function select them and convert the list to an array:
3.) Append them now in sorted order:
4.) The sort function:
Also see an example.