JSFiddle - React, Tailwind, and code Playground
by serio
HTML
<div id=widget></div>
CSS
img {
float: left;
max-width: 200px;
/* clear: right; */
}
JavaScript
$(function() {
$(window).on('hashchange', function() {
var hash = window.location.hash,
sub = (hash && hash !== '') ? hash.substr(1) : 'cats';
ajaxy(sub);
}).trigger('hashchange');
function format(d) {
var html = '';
$.each(d, function(i) {
// html += template( d[ i ].data );
// console.log( d[ i ].data.url );
var url = d[i].data.url;
var ext = url.substr(url.lastIndexOf('.'));
if (ext === '.jpg' || ext === '.gif' || ext === '.png') {
// console.log( "It's an image, go to town!" );
// html += template( d[ i ].data.url );
$(template(d[i].data.url)).appendTo('#widget');
}
});
return html;
}
function template(img) {
return ['<img src="', img, '" />'].join('');
}
/* function template( d ) {
var tmpl = [
'<div class=post>',
'<h2>',
'<a href="', d.url, '">',
d.title,
' <small>(', d.domain, ')</small>',
'</a>',
'</h2>',
'<div class=content>',
'submitted by ', d.author, '<br />',
'<span class=comments>',
'<a href="http://reddit.com', d.permalink , '">',
d.num_comments, ' comments',
'</a>',
'</div>',
'</div>'
].join( '' );
return tmpl;
} */
function ajaxy(reddit) {
var widget = $('#widget');
$.getJSON('http://www.reddit.com/r/' + reddit + '/.json?jsonp=?&callback=?', function(d) {
widget.empty();
format(d.data.children);
});
}
});