I have a checkbox form that lets users select one or more Twitter timelines to display. Right now, the timelines appear in batches (i.e., all the tweets from first timeline, followed by all the tweets from the second timeline, and so on). I’d like to sort all of the collected tweets into a single chronology before output.
Here is a JS fiddle: http://jsfiddle.net/brianeoneill/z9cuP/2/
$('input[type=submit]').on('click', function(e){
// prevent default behavior of the submit button
e.preventDefault();
// empty the div with ID of tweets
$('#tweets').empty();
// perform a function on all of the checked boxes
$(':checkbox:checked').each( function(){
var twitterID = $(this).attr('data');
// use the "data" attribute to build the query string for getJSON
$.getJSON( 'http://api.twitter.com/1/statuses/user_timeline/'+twitterID+'.json?callback=?', null, function(data){
// create an empty ul
var tweetList = $('<ul id="tweets-list">');
// for each JSON object returned, parse it into an li
$.each(data, function(i, tweet){
var item = $('<li class="'+i+'">');
var name = $('<h2>').text(tweet.user.name);
var date = $('<small>').text(tweet.created_at);
var img = $('<img>').attr('src', tweet.user.profile_image_url);
var msg = $('<p>').text(tweet.text);
item.append(img,name,date,msg);
// add the li to the empty tweetList ul
tweetList.append(item);
}); // end of JSON parse function
// SORT BEFORE SENDING TO DOM
$('#tweets').append(tweetList);
I’ve tried creating an array of li’s and then sorting them by the Twitter timestamp, but I’d always end up with an empty array. So clearly I’m missing something.
Thanks in advance!
Hint: all Tweet IDs are generated chronologically ascending. Doesn’t matter whose timeline a Tweet is from, even can be mixed timelines, if you order Tweets by their ID, you get the right chronological order.