A list of top ten posts from a subreddit using redditjs api. Working jsfiddle http://jsfiddle.net/KobaKhit/t42zkbnk/
<!-- Produces a responsive list of top ten posts from a subreddit /worldnews. Working jsfiddle http://jsfiddle.net/KobaKhit/t42zkbnk/ --> | |
<div id="posts"> | |
<h2> Today's top ten news <small>from <a href = '//reddit.com/r/worldnews' target = '_blank'>/r/worldnews</a></small></h2> | |
<hr> | |
<ul class="list-unstyled"></ul> | |
</div> | |
<!-- JS --> | |
<script src="https://rawgit.com/sahilm/reddit.js/master/reddit.js"></script> | |
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script> | |
<script src="https://rawgit.com/davatron5000/FitText.js/master/jquery.fittext.js"></script> <!-- for text scaling --> | |
<script> | |
function correct_url(text) { | |
// Remove the slash from the end of the article link to pass to href | |
var html = $.trim(text); | |
if (html) { | |
html = html.replace(/(\/$)/, ''); | |
} | |
return html; | |
} | |
function reddit_list(news) { | |
// Create alist of top ten posts | |
var l = $('#posts .list-unstyled'); | |
// clear the existing list | |
$('#posts .list-unstyled li').remove(); | |
$.each(news, function (index, obj) { | |
var link = correct_url(obj.url); | |
l.append($("<li></li>") | |
.append($("<p class = 're'></p>") | |
.append("<a class = 'title' target = '_blank' href = " + "http://www." + obj.domain + '></a>') | |
.append("<a target = '_blank' href = " + link + "><text class = 're-title'>" + obj.title + "</text><a/> <a target = '_blank' style = 'color:grey;outline:0' href=http://www." + obj.domain + '>(' + obj.domain + ')</a>')) | |
.append($("<p class='re-under'><a target = '_blank' href = " + 'http://reddit.com' + obj.permalink + " style = 'outline:0'><font color='grey'><b>(score: " + obj.score + ' | comments: ' + obj.num_comments + ') on reddit.com</b></font></a><p>')) | |
); | |
}); | |
// Scale text so its responsive | |
jQuery(".re-under").fitText(6, { | |
minFontSize: '9px', | |
maxFontSize: '14px' | |
}); | |
} | |
// Fetch the 10 top posts on /r/worldnews using redditjs api | |
var news = []; | |
reddit.top('worldnews').t('day').limit(10).fetch(function (res) { | |
// console.log(res); | |
for (var i = 0; i < res.data.children.length; i++) { | |
// res contains JSON parsed response from Reddit | |
news.push(res.data.children[i].data); | |
} | |
reddit_list(news); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment