Twitter provides a public search API in JSONP format. You simply pass the q variable with your search term to Twitter and the server will return a JSON object containing your search results. Bear in mind that search results may vary depending on various factors, including the popularity of the search term and the number of times a given term has been mentioned on Twitter. So if you run a search for your full name, you'll probably get no results but if you try to perform the same search for your Twitter username, it's likely that you get some results, especially if you've been mentioned by some users. In this article we'll see how to run our searches on Twitter using the JSONP API.

Creating a plugin

We need to create a plugin for wrapping up all the necessary routines, including:

  1. the search term
  2. the number of search results we want to display
  3. dates formatting
  4. URLs formatting
  5. fetching the JSON feed

Here's the basic structure of our plugin:

(function($) {

    $.fn.searchTwitter = function(options) {
    
    	var that = this; // reference to the current element
    
    };
    
})(jQuery);

Plugin options

We need only two options, namely the search term and the number of results:

var settings = {
        
    term: '',
    limit: 3
        
};
        
options = $.extend(settings, options);

Hiding the logic with an object

We're going to create a private object to encapsulate all the logic behind our plugin:

var Search = new function() {
        
    var url = 'http://search.twitter.com/search.json?callback=?&q=' + options.term;
    var html = '';
    
}();

url contains the full URL of the JSONP feed, including the search term. html is a string that will contain the markup generated during the parsing of the feed.

Formatting dates and URLs

We'll add two private methods to our object in order to format dates and URLs:

var prettyDate = function(time) {
        
        var date = new Date((time || "").replace(/-/g,"/").replace(/TZ/g," ")),
            diff = (((new Date()).getTime() - date.getTime()) / 1000),
            day_diff = Math.floor(diff / 86400);
                
        if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
            return;
        var v = day_diff == 0 && (
                diff < 60 && "now" ||
                diff < 120 && "1 minute ago" ||
                diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
                diff < 7200 && "1 hour ago" ||
                diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
            day_diff == 1 && "yesterday" ||
            day_diff < 7 && day_diff + " days ago" ||
            day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
        if (!v)
            window.console && console.log(time);
        return v ? v : '';
        }
        
        var formatTweet = function(text) {
        
            var tweet = '';
            
            tweet = text.replace(/(http:\/\/\S+)/g, '<a href="$1">$1</a>');
            tweet = tweet.replace(/\@(\w+)/g, '<a href="http://twitter.com/$1">@$1</a>');
            
            return tweet;
        
        };

Running the search

Our object has only one public method which is used to fetch and parse the remote feed:

this.run = function() {
            
                
            
                $.getJSON(url, function(data) {
                
                
                    $.each(data.results, function(i, item) {
                    
                        
                        
                        html += '<div class="tweet">';
                        html += '<div class="from">' + '<a href="http://www.twitter.com/'+ item.from_user +'/status/'+ item.id_str +'">' 
                                  + item.from_user + '</a></div>';
                        html += '<p>' + formatTweet(item.text) + '<small>' + prettyDate(item.created_at) + '</small></p>';
                        html += '</div>';
                      
                        return i < (options.limit - 1);
                    
                    });
                    
                    $(html).appendTo(that);
                

                });
                
            
};

The returned JSON object contains results which, in turn, is an array of objects. Each object has the following relevant properties:

  • from_user: the username of the author of the tweet
  • id_str: the ID of the returned tweet
  • text: the content of the tweet
  • created_at: the date of the tweet.

To display only a given number of results we simply exit from the main $.each() loop:

return i < (options.limit - 1);

Finally, we invoke our method within the plugin:

return that.each(function() {
      
    Search.run();
                
      
});

Sample usage

$(function() {
    $('#twitter').searchTwitter({
        term: 'jquery',
        limit: 5
    });
    
});

You can see the demo and the complete code below.

Demo

Live demo