Skip to content

Instantly share code, notes, and snippets.

@zachlysobey
Last active December 15, 2015 20:48
Show Gist options
  • Select an option

  • Save zachlysobey/5320978 to your computer and use it in GitHub Desktop.

Select an option

Save zachlysobey/5320978 to your computer and use it in GitHub Desktop.
Function which grabs a random photo from a specified public facebook (page) album with optional size parameter.
<!-- make sure to include jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
// optional 3rd parameter is the "size" (between 0-9). Default is 5
// Facebook returns several sizes;
// experiment with these and fine-tune with css.
function randomFbPhoto (el, albumId, size) {
var $el = $(el); // create jQuery element from css selector
var dataUrl = "https://graph.facebook.com/fql?q=SELECT+images,+caption,+link,+created+FROM+photo+WHERE+album_object_id+=+" + albumId + "+ORDER+BY+rand()+LIMIT+1";
size = size || 5; // default size to 5
$.getJSON(dataUrl, function (obj) { // parse JSON returned by dataUrl
var data = obj.data[0]; // get through to the meat of the JSON data
var imageSrc = data.images[size].source; // get image source from JSON data
var linkHref = data.link;
var $a = $('<a>').attr({
'href': linkHref,
'target': '_blank' // makes the link open in new tab
});
var $img = $('<img>').attr('src', imageSrc); // build img element
var $caption = $('<p>').text(data.caption).addClass('caption'); // build p.caption element with JSON data
var $created_time = $('<p>').text(data.created).addClass('created_time');
console.log(data);
$a.append($img, $caption, $created_time); // put image and caption into the link
$el.append($a); // append to specified element
});
}
// usage example
$(document).ready(function () {
var albumId = '10151421952604495';
randomFbPhoto('#destination', albumId, 6);
});
</script>
<div id="destination"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment