Skip To Main Content

jQuery Twitter Search Feed

Posted by Boaz Sender

Aug 10 2010

I wrote a dead simple twitter search API implementation with jQuery for bocoup.com yesterday. Everything is explained in the comments. Hopefully this script helps you implement your own twitter feed. You can see the live demo running off to the right.

jQuery.twitterFeed.js

$(function(){
  // Get the JSON of your twitter search, it helps to format these over at search.twitter.com
  $.getJSON('http://search.twitter.com/search.json?q=%40bocoup&callback=?', function(tweets){
    var $tweets = $('<ul>')          // The variable we'll store our tweets in

    for(var i = 0; i < 5; i++){      // Lets get five tweets. Change this to for(var i in tweets.results) get all available results

      var tweet = tweets.results[i], // A variable representing each tweet (for cleanliness sake)
        $tweet = $('<li>');      // The variable we'll temporarily store each tweet in

        // Make the avatare, and append it to the $tweet
        $('<a/>', {
          href: 'http://twitter.com/' + tweet.from_user,
          html: '<img src="' + tweet.profile_image_url + '"/>'
        }).appendTo($tweet);

        // Make the tweet text, and append it to the $tweet
        $('<span>', {
          className: 'content',
          html: '<strong><a href="http://twitter.com/' + tweet.from_user + '">@' + tweet.from_user + '</a>: ' + tweet.text + '</strong>'
        }).appendTo($tweet);

        // Append the $tweet to the $tweets
        $tweet.appendTo($tweets);
    }

    // Clear out the loading text
    $('.twitter-posts').html('')

    // Append the $tweets to the DOM
    $tweets.appendTo('.twitter-posts')

  });
});

I’ve also included some styles in the Gist.

jQuery.twitterFeed.css

.twitter-posts li       {margin-bottom: 10px; font-size: 12px; clear: both; list-style-type:none;}
.twitter-posts li img   {float:left; margin:0px 10px 10px 0px;border:1px solid #c2c2c2; -moz-box-shadow: 0px 0px 4px #c2c2c2;  -webkit-box-shadow: 0px 0px 4px #c2c2c2; box-shadow: 0px 0px 4px #c2c2c2;}

And your HTML should look something like this:

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Dead Simple Twitter Search API jQuery Feed</title>
    <script src="http://code.jquery.com/jquery.js"></script>
    <script src="jQuery.twitterFeed.js"></script>
    <link href="jQuery.twitterFeed.css" media="screen" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <h1>Twitter Posts:</h1>
    <div class="twitter-posts"><h3>Loading Tweets From The Cloud With AJAX HTML5...</h3></div>
  </body>
</html>

Comments

We moved off of Disqus for data privacy and consent concerns, and are currently searching for a new commenting tool.

Contact Us

We'd love to hear from you. Get in touch!