May 30th, 2012 - by Golgotha

In this article we will build an RSS / Twitter news-feed-reader-ticker. Yeah, that’s a mouth full, but you know what I’m talking about, right? This news/RSS/Twitter ticker will query web services using jQuery and return JSON results which we will then display in a scrolling ticker. Oh, hell just click the example below and see for yourself.

Click here to view scrolling ticker

There’s probably a handful of plugins that will achieve the same result, but as you will see there’s not much code needed to do it yourself. Let’s look at the code now.

javascript
< view plain text >
  1. var feedItems = [];
  2. var twitterUser = "scottgu";
  3.  
  4. //http://developer.yahoo.com/yql/console/
  5. var feed1 = {
  6.     url: 'http://query.yahooapis.com/v1/public/yql?q=select%20title%2Clink%2CpubDate%20from%20rss%20where%20url%3D%22http%3A%2F%2Fweblogs.asp.net%2Fscottgu%2Frss.aspx%22&format=json&diagnostics=true&callback=?',
  7.     type: 'rss'
  8. };
  9.  
  10. var feed2 = {
  11.     url: 'http://search.twitter.com/search.json?callback=?&rpp=15&since_id=0&q=from:' + twitterUser,
  12.     type: 'twitter'
  13. };

The first thing we do is create two feed objects. These objects consist of a url and a type. The url points to an external service (Twitter or YQL) that returns the JSON we will use for each item in our feed ticker. The Yahoo Query Language (YQL) service is a really handy tool that allows you to give it an RSS feed url and it then returns JSON. So I’m giving it Scott Guthrie’s RSS feed link. And it now gives me JSON.

I am also using the Twitter service to get tweets from Scott Gu as well. Twitter is nice enough to give us JSON back from their API.

javascript
< view plain text >
  1. //RSS
  2. var request1 = $.getJSON(feed1.url, function (data) {
  3.     $.each(data.query.results.item, function (i, value) {
  4.  
  5.         // Before we continue we check that we got data
  6.         if (value.title !== undefined) {
  7.  
  8.             var sub2 = value.pubDate.substring(0, 16);
  9.  
  10.             var item = {
  11.                 url: value.link,
  12.                 message: value.title,
  13.                 from: feed1.type,
  14.                 date: sub2
  15.             };
  16.             feedItems.push(item);
  17.         }
  18.     });
  19. });
  20.  
  21. //Twitter
  22.  
  23. var request2 = $.getJSON(feed2.url, function (data) {
  24.     $.each(data.results, function (i, value) {
  25.         // Before we continue we check that we got data
  26.         if (value.text !== undefined) {
  27.             // Calculate how many hours ago was the tweet posted
  28.             var dateOf = new Date(value.created_at);
  29.             var dateNow = new Date();
  30.             var dateDiff = dateNow - dateOf;
  31.             var hours = Math.round(dateDiff / (1000 * 60 * 60));
  32.  
  33.             var item = {
  34.                 url: "http://twitter.com/#!/" + twitterUser + '/status/' + value.id_str,
  35.                 message: value.text,
  36.                 from: feed2.type,
  37.                 date: hours + " hours ago"
  38.             };
  39.             feedItems.push(item);
  40.         }
  41.     });
  42. });
  43.  
  44. $.when(request1, request2).then(function () {
  45.     BuildFeedReader();
  46. });

The next thing to do is use jQuery’s jQuery.getJSON() to call the YQL and Twitter services. These services return JSON arrays, which we then loop through. With each iteration we build an item object and add it to our feedItems array. When we are done our feedItems array will hold all the items for each line in our feed ticker.

The jQuery.when() method is perfect here, because it provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. Which is exactly what we have here. So when BOTH asynchronous events are complete we call the BuildFeedReader method.

javascript
< view plain text >
  1. function BuildFeedReader() {
  2.     $.shuffle(feedItems);
  3.  
  4.     var strBuilder = "";
  5.     $.each(feedItems, function (index, value) {
  6.         strBuilder += '<dd class="feed-' + value.from + '"><a href="' + value.url + '" target="_blank" ><div>' + value.date + '</div>' + value.message + '</a></dd>';
  7.     });
  8.  
  9.     var ticker = $("#ticker");
  10.     ticker.html(strBuilder);
  11.  
  12.     //animator function
  13.     function animator(currentItem) {
  14.         //work out new anim duration
  15.         var distance = currentItem.height();
  16.         duration = (distance + parseInt(currentItem.css("marginTop"))) / 0.02;
  17.         //animate the first child of the ticker
  18.         currentItem.animate({ marginTop: -distance }, duration, "linear", function () {
  19.             //move current item to the bottom
  20.             currentItem.appendTo(currentItem.parent()).css("marginTop", 0);
  21.             //recurse
  22.             animator(currentItem.parent().children(":first"));
  23.         });
  24.     };
  25.  
  26.     //start the ticker
  27.     animator(ticker.children(":first"));
  28.     //set mouseenter
  29.     ticker.mouseenter(function () {
  30.         //stop current animation
  31.         ticker.children().stop();
  32.     }).mouseleave(function () {
  33.         //resume animation
  34.         animator(ticker.children(":first"));
  35.     });
  36. }

Within the BuildFeedReader function we call $.shuffle(). As the name implies this takes and array and shuffles up its items. This takes our RSS items and our Twitter items and shuffles them up. You can skip this if you don’t want random results.

Next we iterate through our feedItems array building our html string. When done we add the html string to our ticker DOM element.

The last thing we do is add the mouseenter and mouseleave event handlers. On mouseenter we stop the ticker and re-animate it on mouseleave.

javascript
< view plain text >
  1. //Shuffle Array Up
  2. $.fn.shuffle = function () {
  3.     return this.each(function () {
  4.         var items = $(this).children();
  5.         return (items.length) ? $(this).html($.shuffle(items)) : this;
  6.     });
  7. }
  8. $.shuffle = function (arr) {
  9.     for (
  10.             var j, x, i = arr.length; i;
  11.             j = parseInt(Math.random() * i),
  12.             x = arr[--i], arr[i] = arr[j], arr[j] = x
  13.         );
  14.     return arr;
  15. }

The last bit of code was our shuffle function used to random up the results of an array.

You are done. Hope your enjoy your RSS feed / Twitter feed ticker.

2 Responses to “RSS / Twitter Feed Reader using jQuery”

1 Danny

I want to use this on a website I’m building and want a certain users tweets…twitter states that search.twitter is not a good way to pull user tweets. Anyway you can make the above using twitters API integrated with Json?

2 Jack from Delaware

We’re having our web person implement this. Thanks for sharing!

mulberry sale spyder womens jacket cheap new balance 574 mulberry outlet cheap new balance 574 arcteryx outlet mulberry sale spyder womens jacket mulberry sale spyder womens jacket mulberry outlet mulberry outlet new balance 574

Popular Articles

Top 10 Commentators


Subscribe to this feed! Subscribe by Email!

Random Bits Podcast

You need to download the Flash player from Adobe

Blogs Worth Reading


    Warning: fopen(./wp-content/themes/big-blue/my_blogroll.php): failed to open stream: Permission denied in /home/mangeletti/search-this.com/wp-content/themes/big-blue/get_blogroll.php on line 5

    Warning: fread() expects parameter 1 to be resource, boolean given in /home/mangeletti/search-this.com/wp-content/themes/big-blue/get_blogroll.php on line 6

    Warning: fclose() expects parameter 1 to be resource, boolean given in /home/mangeletti/search-this.com/wp-content/themes/big-blue/get_blogroll.php on line 7
  • Smashing Magazine