🤯 50% Off! 700+ courses, assessments, and books

Techy Treasure #2: Twitter Buzz Widget

    Craig Anderson

    Personally I’m not a huge fan of Twitter, but it is all the rage at the moment and even a cynic like me can see that it’s a valuable tool for connecting with your clients. In fact, there was so much buzz about the launch of Everything You Know About CSS Is Wrong! that we’ve added a simple “Twitter Buzz” widget to it’s sales page.

    While building my little widget I couldn’t find anything quite like what I was after, so I threw something together with PHP and jQuery, and now I’d like share it with you.

    The Server-Side Twitter Proxy

    This one’s dead simple. Check it out:

    header("Content-Type: text/xml");
    // replace Foobar with your URL-encoded search term

    Here we simply grab the search results from http://search.twitter.com/search.atom?q=Foobar, and return it straight to the client. We also set the content type of the response to text/xml; without this, jQuery doesn’t know to handle the response as an XML DOM Document.

    Client-Side Twitter Buzz Widget

    With our server-side proxy and jQuery in place, we can start injecting the response into our document. Place a hidden div with the id twitter-buzz somewhere in your document, then include the following JavaScript:

    $(function() {
        $.get("twitter-proxy.php", function(data, status) {
          // check for success
          if(status == "success") {
            // check for entries
            if($("entry", data).size() > 0) {   
              // create the list               
              var list = $("<ul>").get(0);
              // iterate through entries
              $("entry", data).each(function(index, entry) {
                // parse out the details of the tweet
                var authorElement = $("author", entry).get(0);
                var authorName = $("name", authorElement).text();
                var authorUri = $("uri", authorElement).text();
                var authorImage = $("link[rel='image']", entry).attr("href");
                var text = $("title", entry).text();
                // add the tweet to our list
                $(list).append("<li><a href="" + authorUri + "">" +
                    "<img src="" + authorImage + "" alt="" + authorName + "" />" +
                    "</a><span>" + text + "</span>");
              // add the list to the document
              // reveal the area

    This simply grabs the Atom response from the Twitter proxy we created earlier, creates an unordered list of tweets, then adds them to the document. Even if something goes wrong, or the search returns zero tweets, the page won’t be corrupted at all; all we’ll have is a hidden, empty div in the page.

    There are certainly improvements that could be made to this widget, such as adding automatically refreshing itself on a timer and automagically adding links for @replies, but I’ll leave adding these features up to you.