jQuery Get RSS Feed Live Reader

Sam Deering

Use jQuery get rss (with JavaScript) to get a blogs (or websites) display rss feed on your web page. Use Google Ajax Feed API to retrieve the feed items and returns them as a list of feed items to be displayed. The feed can then be customized with your styles to suit your look – for example it could be used as a jQuery news aggregator.

jQuery RSS Viewer Demo Real World Demo

jQuery RSS Plugin Features

  • Automatically load rss feed when your web page loads
  • Refresh button to refresh the jQuery rss feed reader live
  • You can add mutiple rss feeds
  • You can specify a limit of feed items that are returned
  • Displays a loading button while reading rss feeds

jquery-blog-rss-feed

Download Source Files

The jQuery RSS Plugin Code

The jQuery RSS Plugin mainly uses JavaScript to call google.load(feed) to get the rss feed items.

var gfeedfetcher_loading_image="/images/page-images/loader.gif" //Full URL to "loading" image. No need to config after this line!!

google.load("feeds", "1") //Load Google Ajax Feed API (version 1)

function gfeedfetcher(divid, divClass, linktarget){
	this.linktarget=linktarget || "" //link target of RSS entries
	this.feedlabels=[] //array holding lables for each RSS feed
	this.feedurls=[]
	this.feeds=[] //array holding combined RSS feeds' entries from Feed API (result.feed.entries)
	this.feedsfetched=0 //number of feeds fetched
	this.feedlimit=5
	this.showoptions="" //Optional components of RSS entry to show (none by default)
	this.sortstring="date" //sort by "date" by default
	document.write('<div id="'+divid+'" class="'+divClass+'"></div>') //output div to contain RSS entries
	this.feedcontainer=document.getElementById(divid)
	this.itemcontainer="<li>" //default element wrapping around each RSS entry item
}

gfeedfetcher.prototype.addFeed=function(label, url){
	this.feedlabels[this.feedlabels.length]=label
	this.feedurls[this.feedurls.length]=url
}

gfeedfetcher.prototype.filterfeed=function(feedlimit, sortstr){
	this.feedlimit=feedlimit
	if (typeof sortstr!="undefined")
	this.sortstring=sortstr
}

gfeedfetcher.prototype.displayoptions=function(parts){
	this.showoptions=parts //set RSS entry options to show ("date, datetime, time, snippet, label, description")
}

gfeedfetcher.prototype.setentrycontainer=function(containerstr){  //set element that should wrap around each RSS entry item
this.itemcontainer="< "+containerstr.toLowerCase()+">"
}

gfeedfetcher.prototype.init=function(){
	this.feedsfetched=0 //reset number of feeds fetched to 0 (in case init() is called more than once)
	this.feeds=[] //reset feeds[] array to empty (in case init() is called more than once)
	this.feedcontainer.innerHTML='<p><img class="textmiddle" src="'+gfeedfetcher_loading_image+'" /> Loading blog feeds...</p>'
	var displayer=this
	for (var i=0; i<this .feedurls.length; i++){ //loop through the specified RSS feeds' URLs
		var feedpointer=new google.feeds.Feed(this.feedurls[i]) //create new instance of Google Ajax Feed API
		var items_to_show=(this.feedlimit<=this.feedurls.length)? 1 : Math.floor(this.feedlimit/this.feedurls.length) //Calculate # of entries to show for each RSS feed
		if (this.feedlimit%this.feedurls.length>0 &amp;&amp; this.feedlimit>this.feedurls.length &amp;&amp; i==this.feedurls.length-1) //If this is the last RSS feed, and feedlimit/feedurls.length yields a remainder
			items_to_show+=(this.feedlimit%this.feedurls.length) //Add that remainder to the number of entries to show for last RSS feed
		feedpointer.setNumEntries(items_to_show) //set number of items to display
		feedpointer.load(function(label){
			return function(r){
				displayer._fetch_data_as_array(r, label)
			}
		}(this.feedlabels[i])) //call Feed.load() to retrieve and output RSS feed.
	}
}


gfeedfetcher._formatdate=function(datestr, showoptions){
	var itemdate=new Date(datestr)
	var parseddate=(showoptions.indexOf("datetime")!=-1)? itemdate.toLocaleString() : (showoptions.indexOf("date")!=-1)? itemdate.toLocaleDateString() : (showoptions.indexOf("time")!=-1)? itemdate.toLocaleTimeString() : ""
	return "<span class='datefield'>"+parseddate+"</span>"
}

gfeedfetcher._sortarray=function(arr, sortstr){
	var sortstr=(sortstr=="label")? "ddlabel" : sortstr //change "label" string (if entered) to "ddlabel" instead, for internal use
	if (sortstr=="title" || sortstr=="ddlabel"){ //sort array by "title" or "ddlabel" property of RSS feed entries[]
		arr.sort(function(a,b){
		var fielda=a[sortstr].toLowerCase()
		var fieldb=b[sortstr].toLowerCase()
		return (fielda<fieldb )? -1 : (fielda>fieldb)? 1 : 0
		})
	}
	else{ //else, sort by "publishedDate" property (using error handling, as "publishedDate" may not be a valid date str if an error has occured while getting feed
		try{
			arr.sort(function(a,b){return new Date(b.publishedDate)-new Date(a.publishedDate)})
		}
		catch(err){}
	}
}

gfeedfetcher.prototype._fetch_data_as_array=function(result, ddlabel){	
	var thisfeed=(!result.error)? result.feed.entries : "" //get all feed entries as a JSON array or "" if failed
	if (thisfeed==""){ //if error has occured fetching feed
		alert("Some blog posts could not be loaded: "+result.error.message)
	}
	for (var i=0; i<thisfeed .length; i++){ //For each entry within feed
		result.feed.entries[i].ddlabel=ddlabel //extend it with a "ddlabel" property
	}
	this.feeds=this.feeds.concat(thisfeed) //add entry to array holding all feed entries
	this._signaldownloadcomplete() //signal the retrieval of this feed as complete (and move on to next one if defined)
}

gfeedfetcher.prototype._signaldownloadcomplete=function(){
	this.feedsfetched+=1
	if (this.feedsfetched==this.feedurls.length) //if all feeds fetched
		this._displayresult(this.feeds) //display results
}


gfeedfetcher.prototype._displayresult=function(feeds){
	var rssoutput=(this.itemcontainer=="<li>")? "<ul>n" : ""
	gfeedfetcher._sortarray(feeds, this.sortstring)
	for (var i=0; i<feeds .length; i++){
		var itemtitle="<a rel="nofollow" href="" + feeds[i].link + "" target="" + this.linktarget + "" class="titlefield">" + feeds[i].title + ""
		var itemlabel=/label/i.test(this.showoptions)? '<span class="labelfield">['+this.feeds[i].ddlabel+']</span>' : " "
		var itemdate=gfeedfetcher._formatdate(feeds[i].publishedDate, this.showoptions)
		var itemdescription=/description/i.test(this.showoptions)? "<br />"+feeds[i].content : /snippet/i.test(this.showoptions)? "<br />"+feeds[i].contentSnippet  : ""
		rssoutput+=this.itemcontainer + itemtitle + " " + itemlabel + " " + itemdate + "n" + itemdescription + this.itemcontainer.replace("< ", "</") + "nn"
	}
	rssoutput+=(this.itemcontainer=="<li>")? "</feeds></ul>" : ""
	this.feedcontainer.innerHTML=rssoutput
}

HTML Code

<div id="rssfeed-wrap">
<script type="text/javascript">
var newsfeed=new gfeedfetcher("rssfeeds", "rssfeedsclass", "_new")
newsfeed.addFeed("JQUERY BLOG", "http://www.jquery4u.com/feed/");
newsfeed.addFeed("BLOGOOLA's Blog", "http://blogoola.com/blog/feed/");
newsfeed.displayoptions("label datetime snippet");
newsfeed.setentrycontainer("p");
newsfeed.filterfeed(10, "date");
newsfeed.init();
</script>
<p><a class="darklink" href="javascript:newsfeed.init()">Refresh live blog posts</a></p>
</div>

CSS Code

/** RSS FEED **/
.labelfield{ color:brown; font-size: 90%; }
.datefield{ color:gray; font-size: 90%;}
#rssfeeds a{ color: purple;text-decoration: none;font-weight: bold;}
#rssfeeds p{ margin-bottom: 2px;}
code{ color: red;}
#blogoolafeed, #blogoolafeed a { color:white; }
#blogoolafeed a:hover{ color:#8E7BD3; }
#blogoolafeed ul { margin-left:-15px }
#rssfeed-wrap { text-align:left; margin-left:15px; }

Plugin source: http://www.dynamicdrive.com

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://boliviawebdirectory.com Pedro Salas

    Great, Just what I was looking for! I’ve been searching for such a solution for three days! Thanks for sharing!

  • http://beben-koben.blogspot.com/ Beben Koben

    dynamic drive its a great web, and this is great too, thanks bos for tut’s m/

  • http://www.davidsheardown.com dsheardown

    Hey cool, thank you.. have been trying to get something to work with remote feeds and without having to write proxies, so great stuff!

  • xtheunknown0

    This is seriously good. All I’ve wanted is a reader that can limit the number of items downloaded for each feed. This is actually really hard to find (current time of writing) with Google.

    I’m still hoping for a Windows equivalent to newsbeuter (Linux).

  • Kakulash

    This is exactly what I needed. Thank you!

    Is there anyway to limit the number of total results?

    If I am grabbing posts from 20 different blogs, how do I show just 5?

  • appu

    is there any way to remove duplicate itemtitle

  • julie

    thanks! You made this very easy.

  • http://iamcreative.me Aaron @ iamcreative.me

    Thanks, this is exactly what I needed, thanks for sharing your knowledge.

  • peter

    how can i increase the number of characters in feed description, please help

  • Charles

    Need a way to combine all feeds (from say, 10 sources) into one big feed, then show on HTML just the one most-recent feed from all of them. This doesn’t do it.

    • jquery4u

      @Peter – You’ll need to do some string manipulation on the itemdescription parameter.

      var newLength = 52; //trim to 52 characters only
      itemdescription = itemdescription.substring(0,newLength) + ‘…';

      ” var itemdescription=/description/i.test(this.showoptions)? “
      “+feeds[i].content : /snippet/i.test(this.showoptions)? “
      “+feeds[i].contentSnippet : “”
      rssoutput+=this.itemcontainer + itemtitle + ” ” + itemlabel + ” ” + itemdate + “n” + itemdescription + this.itemcontainer.replace(“<”, “

      @Charles – sounds like you need to grab the latest 1 post from each of the 10 feeds then compare the time and display the latest. I’ll have a look around see if there is already a plugin which does this for you.

  • David

    Thanks for this. I am having a problem though.

    When I put this in on my page, I get the error: ‘newsfeed’ is null or not an object.

    Any idea what might be causing this error? Is it the feed address?

  • http://www.twitter.com/chsweb Jono

    What changes need to be made so that the feed also displays the Post image? Is this possible?

    • http://jquery4u.com/ jQuery4u

      Hi Jono, yes I’m working on such a plugin will be posted on the blog soon, stay tuned!
      Sam

  • Simon

    I d be very interested in that as well:

    Can the reader styled to fetch the images of the rss feeds?

    Have you already found a solution to Charles’ problem of displaying the latest item only of a greater number of feeds?

    Help is very much appreciated,
    thanks
    Simon

    • http://jquery4u.com/ jQuery4u

      Hi Simon, yes I’m working on such a plugin will be posted on the blog soon, stay tuned!
      Sam

  • Letj Know

    Is there a way to just grab the image from the feed with out grabbing all the content? Why is this so hard…

    • http://jquery4u.com/ jQuery4u

      Hi Letj, yes I’m working on such a plugin will be posted on the blog soon, stay tuned!
      Sam

  • Micke

    Is it possible to format list of items with starting ‘ul’. Something like:

    • Micke

      I found within gfeedfetcher.js

  • http://www.mayurgodhani.com/ Mayur Godhani

    Is it possible to display updated list automatically on specific time interval without pressing “Refresh content” button ?

  • Pingback: 15 Best of jQuery RSS Feed Readers | jQuery4u

  • Mike

    Is there anyway to reverse the result sort order?

  • Supriya Surve

    Really nice code. I was looking for the same. Loved it, Thanks a lot :)