Last active
December 10, 2015 04:28
-
-
Save afgomez/4380648 to your computer and use it in GitHub Desktop.
Get the last tweet from any user
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* jQuery.lastTweet | |
* ---------------- | |
* | |
* Fetch the last tweet from the specified user | |
* | |
* Usage: | |
* | |
* $('#container').lastTweet('username'); | |
* | |
* This will parse URLs and mentions and write them into the `#container` node. | |
*/ | |
;(function($) { | |
"use strict"; | |
/* Cached Regexp for extracting URLs and usernames */ | |
var LINK_REGEXP = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&@#\/%?=~_|!:,.;]*[\-A-Z0-9+&@#\/%=~_|])/ig; | |
var USER_REGEXP = /@([_a-z0-9]+)/ig; | |
/** | |
* Fetches the last tweet and gets the text | |
* @return {jqXHR} | |
*/ | |
function fetchLastTweet(username) { | |
return $.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?callback=?', { | |
screen_name: username, | |
count: 1, | |
exclude_replies: true | |
}).pipe(function(data) { | |
// We're only interested in the text | |
return data[0].text; | |
}); | |
} | |
/** | |
* Parse a tweet to add links to usernames and urls | |
* @param {String} tweet | |
* @return {String} Parsed tweet | |
*/ | |
function parseTweet(tweet) { | |
tweet = tweet.replace(LINK_REGEXP, function(url) { | |
return '<a href="'+url+'">'+url+'</a>'; | |
}).replace(USER_REGEXP, function(reply) { | |
return reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>'; | |
}); | |
return tweet; | |
} | |
/** | |
* The plugin itself. Magic goes here | |
* @param {String} username | |
*/ | |
$.fn.lastTweet = function(username) { | |
fetchLastTweet(username).done(function(tweet) { | |
this.html(parseTweet(tweet)); | |
}.bind(this)); | |
return this; | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment