Twitter jQuery AJAX Test
by brianeoneill
HTML
<div class="container">
<form>
<input type="checkbox" id="colbertreport"><label for="colbertreport">The Colbert Report</label>
<br>
<input type="checkbox" id="thedailyshow"><label for="thedailyshow">The Daily Show</label>
<br>
<input type="submit" value="Submit">
</form>
<div class="results">
<ul class="tweets"></ul>
</div>
</div>
CSS
* { margin:0; padding:0; list-style:none; }
.container { width:80%; margin:30px auto; }
.results { min-height:200px; padding:30px; border:1px solid #ddd; }
label { margin-left:8px; }
input[type=checkbox] { margin-bottom:12px; }
input[type=submit] { padding:4px 8px; margin-bottom:12px; }
JavaScript
var form = $('form'),
results = $('.results'),
holdTweets = [];
form.find('input[type=submit]').on('click', function(e){
e.preventDefault();
var checkedOff = form.find(':checked');
if(checkedOff.length == 0)
{ results.text('You didn\'t select anything!'); }
else
{ getTweets( checkedOff ); }
});
function getTweets(selected) {
$.each( selected, function(){
$.ajax({
url: 'http://api.twitter.com/1/statuses/user_timeline/'+this.id+'.json?callback=?',
dataType: 'jsonp',
success: function(data) { holdTweets.push(this); },
error: function() { results.text('something went wrong'); }
});
});
parseTweets(holdTweets);
}
function parseTweets(twitterJSON) {
twitterJSON.sort(function(a,b) { return a.id - b.id });
$.each(twitterJSON, function(i, tweet){
var listItem = $('<li/>');
listItem.append('<img src="'+tweet.user.profile_image_url+'">');
listItem.append('<h1>'+tweet.user.name+'</h1>');
listItem.append('<span>'+tweet.created_at+'</span>');
listItem.append('<span class="id">'+tweet.id+'</span>');
listItem.append('<p>'+tweet.text+'</p>');
results.find('.tweets').append(listItem);
});
}