A Simple Reddit Feed

Are you interested in putting a simple Reddit feed on your website? If so, I’ve been playing around with some “quick and simple” ways to make that happen, with a very low overhead.

reddit-feed

Overview

What I did was create a basic jQuery function (redditfeed) that will load up the links and content from a sub-reddit, and display that information in a container. A live example is being displayed a little further down in this post.

The jQuery code allows you to specify the sub-reddit that you want to load the content from, the number of posts to show and where to “render” the content.

How It Works

If you don’t already know, reddit offers API feeds, by default, to all sub-reddits (subs) and user information. The ones we will be focusing on are for sub-reddits.

By simply adding .json (or .xml) to the end of a sub you will get a page displaying the information we will need to consume. Here is an example, http://www.reddit.com/r/gunsandgear/hot.json.

As you can see in the URL, I’ve added .json to the end of the “hot” topics feed.

This will also work with the New, Rising, Controversial and Top and categories of each sub.

Because we are going to be calling this from our page, we have to be able to use some form of JSONP functionality, this is attained by adding ?jsonp={Function Name} to our URL. Since we are going to be using jQuery, it makes this easy by handling that all for us. Here is a code snippet for how that all works.

$.getJSON("http://www.reddit.com/r/gunsandgear/hot.json?jsonp=?", function (data) {
	// Process the JSON Here
});

A sample of the JSON that is returned, so you know what elements you need, is below.

var sample = {
	"kind": "t3",
	"data": {
		"domain": "santsys.com",
		"banned_by": null,
		"media_embed": {},
		"subreddit": "gunsandgear",
		"selftext_html": null, "selftext": "",
		"likes": null, "secure_media": null,
		"link_flair_text": "Blog",
		"id": "28r47w",
		"gilded": 0,
		"secure_media_embed": {},
		"clicked": false,
		"stickied": false,
		"author": "santsys",
		"media": null,
		"score": 1,
		"approved_by": null,
		"over_18": false,
		"hidden": false,
		"thumbnail": "http://a.thumbs.redditmedia.com/UgKQKDXJfwzwJMON.jpg",
		"subreddit_id": "t5_31qk4",
		"edited": false,
		"link_flair_css_class": "",
		"author_flair_css_class": null,
		"downs": 0,
		"saved": false,
		"is_self": false,
		"permalink": "/r/gunsandgear/comments/27ziqh/california_antigun_legislative_update_june_2014/",
		"name": "t3_27ziqh",
		"created": 1403418620.0,
		"url": "http://l.santsys.com/1xPoqx0",
		"author_flair_text": null,
		"title": "California Anti-Gun Legislative Update - June 2014 | S^2 Blog",
		"created_utc": 1403389820.0,
		"ups": 1,
		"num_comments": 0,
		"visited": false,
		"num_reports": null,
		"distinguished": null
	}
};

Expanding on the code that we used earlier, we can loop through all of the returned elements.

$.getJSON("http://www.reddit.com/r/gunsandgear/hot.json?jsonp=?", function (data) {
	$.each(
		data.data.children,
		function(i, post) {
			// Process each post here
		}
	);
});

Reddit Time

The time format that is used by the created and created_utc fields are in the Epoch-second format. This means that the number is the total seconds since Thursday, 1 January 1970.

The calculations I’m using are done using the created_utc value and subtracting it from the current date/time. The basics of that are outlined in the postTime(cTime) function in the code below.

function postTime(cTime) {
	var now = new Date();
	var elapsed = ((now.getTime() / 1000) - cTime);
	var time = '';
	var days = Math.floor(elapsed / (60 * 60 * 24));
	var hours = Math.floor(elapsed / (60 * 60));
	var min = Math.floor(elapsed / 60);
	var sec = Math.ceil(elapsed);

	if (days > 0) { time = days + ' day' + (days > 1 ? 's' : ''); }
	else if (hours > 0) { time = hours + ' hour' + (hours > 1 ? 's' : ''); }
	else if (min > 0) { time = min + ' minute' + (min > 1 ? 's' : ''); }
	else if (sec > 0) { time = sec + ' second' + (sec > 1 ? 's' : ''); }

	return time;
}

Putting It All Together

So, using the simple JSONP API that twitter offers, it’s pretty simple to build something that will display a subs content on your site… here is the sample code that I have put together.

The supported options are sub, feed, and items. The sub is a string containing the name of the sub-reddit you wish to use. The feed is the type of content you want from the sub, for example, hot, new, top, etc. And the items is the number of items you want the feed to display, with a maximum of 100.

The core javascript (redditfeed.js)

(function ($) {
	$.redditfeed = function (userOptions, parent) {

		if (parent == "") { return; }
		if ($(parent).length < 1) { return; }

		var options = {
			sub: 'gunsandgear',
			feed: 'hot',
			items: 5
		};

		$.extend(options, userOptions);

		if (options.items > 100) options.items = 100; // max number of items that can be returned

		var rUrl = "http://www.reddit.com/r/" + encodeURIComponent(options.sub) + "/" + options.feed + ".json?limit=" + options.limit + "&jsonp=?";
		var html = "";

		function postTime(cTime) {
			var now = new Date();
			var elapsed = ((now.getTime() / 1000) - cTime);
			var time = '';
			var days = Math.floor(elapsed / (60 * 60 * 24));
			var hours = Math.floor(elapsed / (60 * 60));
			var min = Math.floor(elapsed / 60);
			var sec = Math.ceil(elapsed);

			if (days > 0) { time = days + ' day' + (days > 1 ? 's' : ''); }
			else if (hours > 0) { time = hours + ' hour' + (hours > 1 ? 's' : ''); }
			else if (min > 0) { time = min + ' minute' + (min > 1 ? 's' : ''); }
			else if (sec > 0) { time = sec + ' second' + (sec > 1 ? 's' : ''); }

			return time;
		}

		// add title
		html = '<h1><a href="http://www.reddit.com/r/' + encodeURIComponent(options.sub) + '">' + options.sub + '</a></h1>';

		$.getJSON(rUrl, function (rawData) {
			$.each(
			rawData.data.children.slice(0, options.items),
			function (i, post) {
				html += '<div class="ritem">';
				html += '<div class="rthumb"><img src="' + post.data.thumbnail + '" /></div>';
				html += '<div class="rcontent"><div class="rtitle"><a href="' + post.data.url + '" target="_blank">' + post.data.title + '</a></div>'
				html += '<div class="rinfo">';
				html += '<a href="' + post.data.permalink + '" target="_blank">View Comments (' + post.data.num_comments + ')</a> | ';
				html += 'Posted ';

				var time = postTime(post.data.created_utc);
				if(time != '') {
					html += time + ' ago';
				}

				html += ' by <a href="http://www.reddit.com/u/' + encodeURIComponent(post.data.author) + '" target="_blank">' + post.data.author + '</a>';
				html += '</div></div>'
				html += '<div class="rclear"></div></div>';
			});
			$(parent).html(html);
		});
	};
})(jQuery);

The CSS that styles the created content

/* REDDIT CSS */

.rclear {
	clear: both;
	content: ".";
	visibility: hidden;
}

.rfeed {
	max-width: 600px;
	margin: 0 auto;
	font-size: 12px;
	font-family: Arial, Helvetica, sans-serif;
}

	.rfeed a, .rfeed a:link, .rfeed a:active, .rfeed a:visited {
		color: #69F;
		text-decoration: none;
	}

		.rfeed a:hover {
			text-decoration: underline;
		}

	.rfeed h1 {
		text-transform: uppercase;
		color: #333;
		font-size: 14px;
		border-bottom: 1px solid #333;
	}

		.rfeed h1 a, .rfeed h1 a:link, .rfeed h1 a:active, .rfeed h1 a:visited {
			color: #333;
			text-decoration: none;
		}

			.rfeed h1 a:hover {
				text-decoration: underline;
			}

.ritem {
	clear: both;
	padding-bottom: 10px;
}

.rthumb {
	float: left;
	padding-right: 10px;
}

	.rthumb img {
		border-radius: 5px;
		max-width: 70px;
	}

.rcontent {
	overflow: hidden;
	line-height: 1em;
}

.rtitle {
	font-size: 1.2em;
	line-height: 1.2em;
	margin-bottom: 2px;
}

.rinfo {
	font-size: .8em;
	color: #666;
}

	.rinfo a, .rinfo a:link, .rinfo a:active, .rinfo a:visited {
		color: #369;
	}

Putting all of this together, you can use it on a page by doing something simple such as the following example.

<html>
<head>
	<title>Reddit Feed Sample</title>
	<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
	<script type="text/javascript" src="redditfeed.js"></script>
	<link type="text/css" href="styles.css" />
</head>
<body>
	<div class="rfeed"></div>

	<script type="text/javascript">
	(function($) {
		$(document).ready(function () {
			$.redditfeed({
				sub: 'gunsandgear',
				feed: 'hot',
				items: 5
			}, '.rfeed');
		})
	})(jQuery);
	</script>
</body>
</html>

You can view the full Reddit API documentation here.

Happy coding!


6/24/2014 – Update to fix time processing; Fix for user options.

Leave a Reply

Your email address will not be published. Required fields are marked *