0

I'm building a HTML list that is very much similar to Facebooks timeline feature. The list will ontain at most 100 items, so performance isn't a requirement.

Unlike Facebook's timeline however, my list would be quite dynamic. For example different events are arrive in realtime and depending on the timestamp, might get prepended to the list, inserted (I can't guarantee that new events will necessarily arrive in time order) and even removed. On top of that, it would be nice to animate updating of the list (add/inser/remove) too, but that's a separate issue.

I wonder what the best strategy to maintain the list (sorted by time of course), once I've built it up with initial data?

Thanks.

SheetJS
  • 22,470
  • 12
  • 65
  • 75
Aimee.S
  • 31
  • 2

2 Answers2

2

As suggested in the other answer, have a data-time property on each element. When new data arrives, locate the first element which data().time is lesser than the new time. If there is such element, use element.before(newElement), otherwise container.append(newElement). This way the list will be kept sorted.

Illustration: http://jsfiddle.net/JXLGR/

georg
  • 211,518
  • 52
  • 313
  • 390
0

There is a nice jquery function for that here. You could implement a data-property on your html element:

<div data-time="1203812823873"></div>

Then you can actually call the function like this something like this:

$(".elements").sortElements(function(aElement0, aElement1) {

   return aElement0.data("time") - aElement1.data("time");

})
ced-b
  • 3,957
  • 1
  • 27
  • 39