Last active
August 29, 2015 14:05
-
-
Save katzefudder/d0c64c2cc0eccd786335 to your computer and use it in GitHub Desktop.
Asynchronous script to call flickr API via JavaScript, displays photos from a flickr set
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var flickr = { | |
apiKey: null, | |
photosetId: null, | |
photos: null, | |
limit: null, | |
url: null, | |
async: false, | |
elementId: false, | |
init: function(apiKey, photosetId, limit, async, elementId) { | |
this.apiKey = apiKey; | |
this.photosetId = photosetId; | |
this.url = 'https://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key='+this.apiKey+'&photoset_id='+this.photosetId+'&format=json&extras=url_m', | |
this.limit = parseInt(limit); | |
this.async = async; | |
this.elementId = elementId; | |
// options passed to callback later | |
var options = { | |
limit: this.limit, | |
photosetId: this.photosetId, | |
async: this.async, | |
elementId: this.elementId | |
} | |
// passing callback to handle async http call | |
this.httpGet(this.url, this.getPhotos, options); | |
return this; | |
}, | |
jsonFlickrApi : function(code) { | |
return code; | |
}, | |
getPhotos : function(response, options) { | |
var execute = 'flickr.'+response; | |
var object = eval(execute); | |
flickr.write(object, options); | |
}, | |
httpGet: function(url, callback, options) { | |
var xmlHttp = null; | |
xmlHttp = new XMLHttpRequest(); | |
xmlHttp.open("GET", url, this.async); | |
xmlHttp.onload = function (e) { | |
if (xmlHttp.readyState === 4) { | |
if (xmlHttp.status === 200) { | |
callback(xmlHttp.responseText, options); | |
} | |
} | |
} | |
xmlHttp.send(null); | |
}, | |
getRandomNumber: function(base) { | |
return Math.floor((Math.random() * (base)) + 1); | |
}, | |
write: function(object, options) { | |
var photos = []; | |
object.photoset.photo.forEach(function(element){ | |
photos.push([element.url_m, element.title]); | |
}); | |
var html = ''; | |
for (var i = 0; i < this.limit; i++) { | |
var random = this.getRandomNumber(photos.length -1); | |
html += '<img src="'+photos[random][0]+'" alt="'+photos[random][1]+'" />'; | |
} | |
var flickrUrl = 'https://www.flickr.com/photos/'+object.photoset.ownername.toLowerCase()+'/sets/'+options.photosetId+'/'; | |
html += '<p class="taken_from">Random '+options.limit+' photos taken from <a href="'+flickrUrl+'" target="_blank">'+flickrUrl+'</a></p>'; | |
html += ''; | |
var element = document.getElementById(options.elementId); | |
element.innerHTML = html; | |
} | |
} | |
document.write('<div id="flickr"></div>'); | |
flickr.init('50b2c88d16b7d6765f8c2f9b9bce844f', '72157644508338618', 4, true, 'flickr'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment