Please see my codepen for this issue here: http://codepen.io/dsm/pen/ewEJb
This app will display two Flickr galleries. I'm trying to separate the function to be completely independent from the function call. However, the only way I can currently get it to work is to hardcode the lines to include the div id '#flickr'. I tried using $(this) instead but does not seem to cooperate.
Any suggestions?
$('#flickr').append('<h2>'+photosetTitle+'</h2>');
$('#flickr').append(theHtml);
The above are the lines of code in question and can be seen in the code below.
Note: this code assumes jquery is already loaded.
(function($){
$.fn.flickrSetGallery = function(callerSettings) {
var settings = $.extend(callerSettings);
var url = 'http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=';
url += settings.apiKey;
url += '&photoset_id=';
url += settings.photosetID;
url += '&format=json&jsoncallback=?';
$.getJSON(url, displayImages);
function displayImages(data) {
var photosetTitle = data.photoset.title;
var photosetTag = photosetTitle.toLowerCase().trim().split(/\s+/).join
var theHtml = "";
$.each(data.photoset.photo, function(i,photo){
var source = 'http://farm'+photo.farm+'.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'_s.jpg';
theHtml+= '<li><a href="http://farm'+photo.farm+'.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'_b.jpg" data-lightbox="'+photosetTag+'">';
theHtml+= '<img title="'+photo.title+'" src="'+source+'" alt="'+photo.title+'" />';
theHtml+= '</a></li>';
});
$('#flickr').append('<h2>'+photosetTitle+'</h2>');
$('#flickr').append(theHtml);
};
};
})(jQuery);
$(document).ready(function() {
$('#flickr').flickrSetGallery({
apiKey: '2eabc9d4b3a1b7443b2900a729b8b4a8',
photosetID: '72157616127960344'
});
$('#flickr2').flickrSetGallery({
apiKey: '403e03feaf4819a91a02f158a0504075',
photosetID: '72157637557971086'
});
});
And here is the HTML:
<div id="flickr" class="flickr-things">
</div>
<div id="flickr2" class="flickr-things">
</div>
Try this way, using this
inside the callback doesn't posint to the original element it is jqXhr object, so instead you can just cache it to a variable and use it:
Before tha ajax call:
var flickrContainer = this; //this is already a jquery object here
$.getJSON(url, displayImages);
......
and inside your callback use it as:
flickrContainer.append('<h2>'+photosetTitle+'</h2>');
flickrContainer.append(theHtml);
There are other ways as well like using $.proxy
function.bind
etc to bind the context of the ajax callback to the context of the element.
$.getJSON(url, displayImages.bind(this)); // or $.proxy(displayImages,this)
and now this
inside your function represents the flickerContainer so you can just do:
this.append('<h2>'+photosetTitle+'</h2>');
this.append(theHtml);